在 Python 中,我想将列表中的所有字符串都转换为整数。
所以,如果我有:
results = ['1', '2', '3']
我该怎么做:
results = [1, 2, 3]
使用列表理解:
results = [int(i) for i in results]
例如
>>> results = ["1", "2", "3"]
>>> results = [int(i) for i in results]
>>> results
[1, 2, 3]
比列表理解要扩展一点,但同样有用:
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