的名單我在名單如何字符串列表轉換爲INT
a = [['1','2','3','4'],['1','2','3','4'],['1','2','3','4']]
有這個名單,但我需要它是整數, 林不知道在哪裏可以使用int()來改變海峽使用嵌套list comprehension爲int
a = [[1,2,3,4],[1,2,3,4],[1,2,3,4]]
的名單我在名單如何字符串列表轉換爲INT
a = [['1','2','3','4'],['1','2','3','4'],['1','2','3','4']]
有這個名單,但我需要它是整數, 林不知道在哪裏可以使用int()來改變海峽使用嵌套list comprehension爲int
a = [[1,2,3,4],[1,2,3,4],[1,2,3,4]]
您可以使用嵌套列表comprehe nsion像這樣:
a = [['1','2','3','4'],['1','2','3','4'],['1','2','3','4']]
b = [ [int(j) for j in i] for i in a]
一個例子:
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]]
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]]
這裏有一個想法:
>>> 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]]
非常感謝你 – user1870662