列表列表中的Python“Str to Int”?

时间:2017-09-21 23:15:44

标签: python

我想在列表列表中将元素“str”转换为“int”。

list = [['2003', '12', '5'], ['2004', '10', '7']]

[['2003', '12', 5], ['2004', '10', 7]]

3 个答案:

答案 0 :(得分:1)

重新分配

for x in list:
    x[2] = int(x[2])

建议您不要将变量list命名为与Python内部函数冲突

答案 1 :(得分:0)

您可以使用 list comprehension 创建一个新列表:

>>> my_list = [['2003', '12', '5'], ['2004', '10', '7']]

>>> new_list = [e[:-1]+[int(e[-1])] for e in my_list]
>>> new_list
[['2003', '12', 5], ['2004', '10', 7]]

答案 2 :(得分:0)

您可以在列表理解中使用enumerate

list = [['2003', '12', '5'], ['2004', '10', '7']]
final_list = [[int(a) if i == 2 else a for i, a in enumerate(b)] for b in list]

最终输出:

[['2003', '12', 5], ['2004', '10', 7]]

编辑:

关于您发布的新输入,您可以尝试:

s = [['1994', '5', '18', '3', '11668'], ['1994', '5', '19', '4', '11411'], ['1994', '5', '20', '5', '11645'], ['1994', '5', '21', '6', '8830'], ['1994', '5', '22', '7', '8449']]
new_s = [[int(a) if i == 3 else a for i, a in enumerate(b)] for b in s]

输出:

[['1994', '5', '18', 3, '11668'], ['1994', '5', '19', 4, '11411'], ['1994', '5', '20', 5, '11645'], ['1994', '5', '21', 6, '8830'], ['1994', '5', '22', 7, '8449']]