如何将列表中的所有字符串转换为整数?
['1', '2', '3'] ⟶ [1, 2, 3]
有几种方法可以将列表中的字符串数字转换为整数。
在Python 2.x中,您可以使用map函数:
>>> results = ['1', '2', '3']
>>> results = map(int, results)
>>> results
[1, 2, 3]
>>> results = ['1', '2', '3']
>>> results = list(map(int, results))
>>> results
[1, 2, 3]
iterator
的映射对象,它将逐个生成结果(值),这就是我们需要添加一个名为list
的函数的原因,该函数将应用于所有可迭代项。map
函数的返回值及其类型。
第三种方法适用于Python 2.x和Python 3.x,即列表推导式。
>>> results = ['1', '2', '3']
>>> results = [int(i) for i in results]
>>> results
[1, 2, 3]
result = ['1','2','3']
,只需执行以下操作:result = [int(item) for item in result]
print(result)
它会给你输出结果,例如:
[1,2,3]
如果您的列表只包含纯整数字符串,那么接受的答案就是正确的选择。如果您提供的东西不是整数,它将崩溃。
因此:如果您的数据可能包含整数、浮点数或其他类型的内容,您可以利用自己的带有错误处理的函数:
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']
如果你想处理嵌套的可迭代对象,可以使用这个辅助函数:
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
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
当输入时,您可以简单地在一行中完成它。
[int(i) for i in input().split("")]
按您所需的位置进行分割。
如果要将列表转换为非列表,请在input().split("")
的位置上放置您的列表名称。
以下是针对您问题的简单解决方案及其解释。
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]
因此,只有当给定的字符串完全由数字组成时,我们才能将列表中的字符串项转换为整数,否则会生成错误。
方法 #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]
方法二:使用列表推导式
# 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]
方法三:使用 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]
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, 0.1]
你可以笑,但它确实有效。
float
而不是int
也可以很好地解决您的用例。 - Karl Knechtel
map
,因此如果您使用该标准,无论如何都需要准备使用列表推导式。 :) - ThorSummonerlist(map(int, results))
,它适用于任何Python版本。 - mvp