我试图将大列表中小列表的所有元素转换为整数,所以它应该如下所示:
current list:
list = [['1','2','3'],['8','6','8'],['2','9','3'],['2','5','7'],['5','4','1'],['0','8','7']]
for e in list:
for i in e:
i = int(i)
new list:
list = [[1,2,3],[8,6,8],[2,9,3],[2,5,7],[5,4,1],[0,8,7]]
有谁可以告诉我为什么这不起作用并向我展示一种有效的方法?谢谢!
答案 0 :(得分:7)
您可以使用嵌套列表解析:
converted = [[int(num) for num in sub] for sub in lst]
我还将list
重命名为lst
,因为list
是列表类型的名称,不建议用于变量名称。
答案 1 :(得分:1)
for e in range(len(List)):
for p in range(len(List[e])):
List[e][p] = int(List[e][p])
或者,您可以创建一个新列表:
New = [list(map(int, sublist)) for sublist in List]
答案 2 :(得分:0)
简而言之,您不会改变lst
:
for e in lst:
for i in e:
# do stuff with i
相当于
for e in lst:
for n in range(len(e)):
i = e[n] # i and e[n] are assigned to the identical object
# do stuff with i
现在,是否"东西"你所做的i
反映在原始数据中,取决于它是否是对象的变异,例如。
i.attr = 'value' # mutation of the object is reflected both in i and e[n]
但是,字符串类型(str
,bytes
,unicode
)和int
在Python中是不可变的,变量赋值不是变异,而是重新绑定操作。
i = int(i)
# i is now assigned to a new different object
# e[n] is still assigned to the original string
因此,您可以使代码正常工作:
for e in lst:
for n in range(len(e)):
e[n] = int(e[n])
或使用较短的理解符号:
new_lst = [[int(x) for x in sub] for sub in lst]
但请注意,前者会改变现有的list
对象lst
,而后者会创建一个新对象new_lst
,使原始对象保持不变。您选择哪一个取决于您的计划的需求。
答案 3 :(得分:0)
嵌套列表理解是最好的解决方案,但您也可以考虑使用lambda函数进行映射:
lista = [['1','2','3'],['8','6','8'],['2','9','3'],['2','5','7'],['5','4','1'],['0','8','7']]
new_list = map(lambda line: [int(x) for x in line],lista)
# Line is your small list.
# With int(x) you are casting every element of your small list to an integer
# [[1, 2, 3], [8, 6, 8], [2, 9, 3], [2, 5, 7], [5, 4, 1], [0, 8, 7]]