问题:将列表中的所有字符串转换为int
在Python中,我想将列表中的所有字符串转换为整数。
所以,如果我有:
results = ['1', '2', '3']
我该如何做:
results = [1, 2, 3]
In Python, I want to convert all strings in a list to integers.
So if I have:
results = ['1', '2', '3']
How do I make it:
results = [1, 2, 3]
回答 0
使用map
功能(在Python 2.x中):
results = map(int, results)
在Python 3中,您需要将结果从map
转换为列表:
results = list(map(int, results))
Use the map
function (in Python 2.x):
results = map(int, results)
In Python 3, you will need to convert the result from map
to a list:
results = list(map(int, results))
回答 1
使用列表理解:
results = [int(i) for i in results]
例如
>>> results = ["1", "2", "3"]
>>> results = [int(i) for i in results]
>>> results
[1, 2, 3]
Use a list comprehension:
results = [int(i) for i in results]
e.g.
>>> results = ["1", "2", "3"]
>>> results = [int(i) for i in results]
>>> results
[1, 2, 3]
回答 2
比列表理解要扩展一点,但同样有用:
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)
例如
>>> results = ["1", "2", "3"]
>>> str_list_to_int_list(results)
[1, 2, 3]
也:
def str_list_to_int_list(str_list):
int_list = [int(n) for n in str_list]
return int_list
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)
e.g.
>>> 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