可能重複:
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]
可能重複:
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]
使用地圖功能(在PY2):
results = map(int, results)
在PY3:
results = list(map(int, results))
我想指出,pylint不鼓勵使用'地圖',所以準備無論如何,如果你曾經使用過這個標準,就可以使用列表解析。 :) – ThorSummoner
反過來(將int列表轉換爲字符串列表):map(str,results) –
您可以簡化這個答案:只要總是使用'list(map(int,results))',它適用於任何Python版本。 – mvp
使用列表理解:
results = [int(i) for i in results]
例如,
>>> results = ["1", "2", "3"]
>>> results = [int(i) for i in results]
>>> results
[1, 2, 3]
列表理解也很棒。到OP - 看到這裏看到一個很好的地圖和列表理解的對比:http://stackoverflow.com/questions/1247486/python-list-comprehension-vs-map – cheeken
看到這個:http://stackoverflow.com/questions/642154/how-to-convert-strings-into-integers-in-python –
遺憾的是應該是一個沒有答案的註釋。看到這個答案︰http://stackoverflow.com/questions/642154/how-to-convert-strings-into-integers-in-python –