本文翻译自:Convert all strings in a list to int
In Python, I want to convert all strings in a list to integers. 在Python中,我想将列表中的所有字符串转换为整数。
So if I have: 所以,如果我有:
results = ['1', '2', '3']
How do I make it: 我该如何做:
results = [1, 2, 3]
#1楼
参考:https://stackoom.com/question/UuxR/将列表中的所有字符串转换为int
#2楼
A little bit more expanded than list comprehension but likewise useful: 比列表理解要扩展一点,但同样有用:
def str_list_to_int_list(str_list):
n = 0
while n < len(str_list):
str_list[n] = int(str_list[n])
n += 1
return(str_list)
eg 例如
>>> results = ["1", "2", "3"]
>>> str_list_to_int_list(results)
[1, 2, 3]
Also: 也:
def str_list_to_int_list(str_list):
int_list = [int(n) for n in str_list]
return int_list
#3楼
Use the map
function (in Python 2.x): 使用map
函数(在Python 2.x中):
results = map(int, results)
In Python 3, you will need to convert the result from map
to a list: 在Python 3中,您需要将结果从map
转换为列表:
results = list(map(int, results))
#4楼
Use a list comprehension : 使用列表理解 :
results = [int(i) for i in results]
eg 例如
>>> results = ["1", "2", "3"]
>>> results = [int(i) for i in results]
>>> results
[1, 2, 3]