如何将字符串列表转换为int列表

时间:2012-12-02 19:15:40

标签: python python-3.x

我在列表中列出了这个列表

a = [['1','2','3','4'],['1','2','3','4'],['1','2','3','4']]

但我需要它成为一个整体, 我不知道在哪里使用int()将str更改为int

a = [[1,2,3,4],[1,2,3,4],[1,2,3,4]]

4 个答案:

答案 0 :(得分:3)

您可以使用嵌套列表理解,如下所示:

a = [['1','2','3','4'],['1','2','3','4'],['1','2','3','4']]
b = [ [int(j) for j in i] for i in a]

答案 1 :(得分:1)

In [51]: a = [['1','2','3','4'],['1','2','3','4'],['1','2','3','4']]

In [52]: [map(int, l) for l in a]
Out[52]: [[1, 2, 3, 4], [1, 2, 3, 4], [1, 2, 3, 4]]

答案 2 :(得分:0)

使用嵌套list comprehension的示例:

In [1]: a = [['1','2','3','4'],['1','2','3','4'],['1','2','3','4']]

In [2]: [[int(s) for s in l] for l in a]
Out[2]: [[1, 2, 3, 4], [1, 2, 3, 4], [1, 2, 3, 4]]

答案 3 :(得分:0)

这是一个想法:

>>> a = [['1','2','3','4'],['1','2','3','4'],['1','2','3','4']]
>>> map(lambda l: map(int, l), a)
[[1, 2, 3, 4], [1, 2, 3, 4], [1, 2, 3, 4]]