如何将列表中的项转换为另一个列表中的项,将它们从char转换为int


[['1', '1'], ['1', '2'], ['1', '3'], ['1', '4'], ['2', '1'], ['2', '2'], ['2', '5'], ['3', '3'], ['3', '4'], ['3', '6'], ['4', '5'], ['5', '6']]

这是我得到的,但我试图返回:

[[1,1], [1,2], [1,3], [1,4]...etc

取文件每行的代码:

##takes each line of the text file
filename = input("Enter filename:")
with open(filename) as file_in:
lines = []
for line in file_in:
words = line.split()
lines.append(words)

遍历每个"words"并将它们转换为int,使用类似int(word)的东西。请注意,如果字符串没有被格式化为int类型,则可能会抛出异常,因此包含try/catch

是明智的。

遍历子列表并键入int

nested = [['1', '1'], ['1', '2'], ['1', '3'], ['1', '4'], ['2', '1'], ['2', '2'], ['2', '5'], ['3', '3'], ['3', '4'], ['3', '6'], ['4', '5'], ['5', '6']]
final = [[int(e) for e in item] for item in nested]
print(final)

给了#

[[1, 1], [1, 2], [1, 3], [1, 4], [2, 1], [2, 2], [2, 5], [3, 3], [3, 4], [3, 6], [4, 5], [5, 6]]

remove()方法从列表中删除作为参数传递的第一个匹配元素pop()方法删除给定索引处的元素,并将被删除的项作为0

最新更新