2011-09-10 54 views
343

可能重複:
How to convert strings into integers in python?
How to convert a string list into an integer in python轉換所有字符串列表來詮釋

在蟒蛇,我想所有的字符串轉換列表中以整數。

所以,如果我有:

results = ['1', '2', '3'] 

如何使它:

results = [1, 2, 3] 
+0

看到這個:http://stackoverflow.com/questions/642154/how-to-convert-strings-into-integers-in-python –

+0

遺憾的是應該是一個沒有答案的註釋。看到這個答案︰http://stackoverflow.com/questions/642154/how-to-convert-strings-into-integers-in-python –

回答

720

使用地圖功能(在PY2):

results = map(int, results) 

在PY3:

results = list(map(int, results)) 
+9

我想指出,pylint不鼓勵使用'地圖',所以準備無論如何,如果你曾經使用過這個標準,就可以使用列表解析。 :) – ThorSummoner

+1

反過來(將int列表轉換爲字符串列表):map(str,results) –

+0

您可以簡化這個答案:只要總是使用'list(map(int,results))',它適用於任何Python版本。 – mvp

217

使用列表理解:

results = [int(i) for i in results] 

例如,

>>> results = ["1", "2", "3"] 
>>> results = [int(i) for i in results] 
>>> results 
[1, 2, 3] 
+22

列表理解也很棒。到OP - 看到這裏看到一個很好的地圖和列表理解的對比:http://stackoverflow.com/questions/1247486/python-list-comprehension-vs-map – cheeken