如何将列表中的所有字符串转换为整数?
['1', '2', '3'] ⟶ [1, 2, 3]
如何将列表中的所有字符串转换为整数?
['1', '2', '3'] ⟶ [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)
e.g.
>>> 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
其他回答
使用python中的循环简写,可以轻松地将字符串列表项转换为int项
假设你有一个字符串result = ['1','2','3']
就做,
result = [int(item) for item in result]
print(result)
它会给你输出
[1,2,3]
考虑到:
xs = ['1', '2', '3']
使用map then list获取一个整数列表:
list(map(int, xs))
在Python 2中,list是不必要的,因为map返回一个列表:
map(int, xs)
在列表xs上使用一个列表推导式:
[int(x) for x in xs]
e.g.
>>> xs = ["1", "2", "3"]
>>> [int(x) for x in xs]
[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)
e.g.
>>> 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
下面的答案,即使是最流行的答案,也并非适用于所有情况。我有这样一个解决方案的超级抗推力str。 我有这样一件事:
AA =[’0’、160。5,160。5、160。1、160。1、160。1,1 160。]
AA = pd.DataFrame(AA, dtype=np.float64)
AA = AA.values.flatten()
AA = list(AA.flatten())
AA
[0.0, 0.5, 0.5, 0.1, 0.1, 0.1]
你可以笑,但这很有效。