如何将列表中的所有字符串转换为整数?
['1', '2', '3'] ⟶ [1, 2, 3]
如何将列表中的所有字符串转换为整数?
['1', '2', '3'] ⟶ [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]
其他回答
考虑到:
xs = ['1', '2', '3']
使用map then list获取一个整数列表:
list(map(int, xs))
在Python 2中,list是不必要的,因为map返回一个列表:
map(int, xs)
如果您的列表包含纯整数字符串,接受的答案是要走的路。如果输入的不是整数它就会崩溃。
所以:如果你的数据可能包含int,可能是浮点数或其他东西-你可以利用你自己的函数errorhandling:
def maybeMakeNumber(s):
"""Returns a string 's' into a integer if possible, a float if needed or
returns it as is."""
# handle None, "", 0
if not s:
return s
try:
f = float(s)
i = int(f)
return i if f == i else f
except ValueError:
return s
data = ["unkind", "data", "42", 98, "47.11", "of mixed", "types"]
converted = list(map(maybeMakeNumber, data))
print(converted)
输出:
['unkind', 'data', 42, 98, 47.11, 'of mixed', 'types']
要处理可迭代对象内部的可迭代对象,你可以使用这个helper:
from collections.abc import Iterable, Mapping
def convertEr(iterab):
"""Tries to convert an iterable to list of floats, ints or the original thing
from the iterable. Converts any iterable (tuple,set, ...) to itself in output.
Does not work for Mappings - you would need to check abc.Mapping and handle
things like {1:42, "1":84} when converting them - so they come out as is."""
if isinstance(iterab, str):
return maybeMakeNumber(iterab)
if isinstance(iterab, Mapping):
return iterab
if isinstance(iterab, Iterable):
return iterab.__class__(convertEr(p) for p in iterab)
data = ["unkind", {1: 3,"1":42}, "data", "42", 98, "47.11", "of mixed",
("0", "8", {"15", "things"}, "3.141"), "types"]
converted = convertEr(data)
print(converted)
输出:
['unkind', {1: 3, '1': 42}, 'data', 42, 98, 47.11, 'of mixed',
(0, 8, {'things', 15}, 3.141), 'types'] # sets are unordered, hence diffrent order
在列表xs上使用一个列表推导式:
[int(x) for x in xs]
e.g.
>>> xs = ["1", "2", "3"]
>>> [int(x) for x in xs]
[1, 2, 3]
使用python中的循环简写,可以轻松地将字符串列表项转换为int项
假设你有一个字符串result = ['1','2','3']
就做,
result = [int(item) for item in result]
print(result)
它会给你输出
[1,2,3]
在获取输入时,只需在一行中完成。
[int(i) for i in input().split("")]
你想在哪分就在哪分。
如果你想转换一个列表而不是列表,只需把你的列表名称放在input().split("")的位置。