列表的列表,将所有字符串转换为整数,Python 3

4
我正在尝试将大列表中的所有小列表元素转换为整数,因此它应该看起来像这样:
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]]

有人能告诉我为什么这不起作用,然后给我一个可行的方法吗?谢谢!


通过赋值 i = int(i),你将覆盖变量 i 中的引用,但不是列表内部的值。 - Mirac7
@Mirac7 谢谢! - ufiufi
如果我只想转换每个列表中的第三个值怎么办? [['1','2',3],['8','6',8],['2','9',3],['2','5',7],['5','4',1],['0','8',7]] - Caio Gomes
4个回答

10

你可以使用嵌套的列表推导式:

converted = [[int(num) for num in sub] for sub in lst]

我还将list重命名为lst,因为list是列表类型的名称,不建议用作变量名。


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]

0

嵌套列表推导式是最好的解决方案,但您也可以考虑使用带有lambda函数的map:

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]]

-1
简而言之,您没有改变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]

然而,在Python中,字符串类型(strbytesunicode)和int是不可变的,并且变量赋值不是一种突变,而是一种重新绑定操作。
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,并保留原始对象不变。你选择哪个取决于你的程序需求。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接