如何将列表中的所有字符串转换为整数?
['1', '2', '3'] ⟶ [1, 2, 3]
如何将列表中的所有字符串转换为整数?
['1', '2', '3'] ⟶ [1, 2, 3]
当前回答
这里有一个简单的解决方案,对您的查询进行了解释。
a=['1','2','3','4','5'] #The integer represented as a string in this list
b=[] #Fresh list
for i in a: #Declaring variable (i) as an item in the list (a).
b.append(int(i)) #Look below for explanation
print(b)
这里,append()用于将项(即本程序中字符串(i)的整数版本)添加到列表(b)的末尾。
注意:int()是一个帮助将字符串形式的整数转换回整数形式的函数。
输出控制台:
[1, 2, 3, 4, 5]
因此,只有当给定的字符串完全由数字组成时,我们才能将列表中的字符串项转换为整数,否则将产生错误。
其他回答
考虑到:
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]
我还想添加Python |将列表中的所有字符串转换为整数
方法1:朴素法
# Python3 code to demonstrate
# converting list of strings to int
# using naive method
# initializing list
test_list = ['1', '4', '3', '6', '7']
# Printing original list
print ("Original list is : " + str(test_list))
# using naive method to
# perform conversion
for i in range(0, len(test_list)):
test_list[i] = int(test_list[i])
# Printing modified list
print ("Modified list is : " + str(test_list))
输出:
Original list is : ['1', '4', '3', '6', '7']
Modified list is : [1, 4, 3, 6, 7]
方法#2:使用列表理解
# Python3 code to demonstrate
# converting list of strings to int
# using list comprehension
# initializing list
test_list = ['1', '4', '3', '6', '7']
# Printing original list
print ("Original list is : " + str(test_list))
# using list comprehension to
# perform conversion
test_list = [int(i) for i in test_list]
# Printing modified list
print ("Modified list is : " + str(test_list))
输出:
Original list is : ['1', '4', '3', '6', '7']
Modified list is : [1, 4, 3, 6, 7]
方法#3:使用map()
# Python3 code to demonstrate
# converting list of strings to int
# using map()
# initializing list
test_list = ['1', '4', '3', '6', '7']
# Printing original list
print ("Original list is : " + str(test_list))
# using map() to
# perform conversion
test_list = list(map(int, test_list))
# Printing modified list
print ("Modified list is : " + str(test_list))
输出:
Original list is : ['1', '4', '3', '6', '7']
Modified list is : [1, 4, 3, 6, 7]
使用python中的循环简写,可以轻松地将字符串列表项转换为int项
假设你有一个字符串result = ['1','2','3']
就做,
result = [int(item) for item in result]
print(result)
它会给你输出
[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