将列表中的所有字符串转换为整数

799

如何将列表中的所有字符串转换为整数?

['1', '2', '3']  ⟶  [1, 2, 3]
11个回答

1482

给定:

xs = ['1', '2', '3']

使用 map 然后 list 来获取一个整数列表:
list(map(int, xs))

在Python 2中,list是不必要的,因为map返回一个列表。
map(int, xs)

34
我想指出,Pylint 不鼓励使用 map,因此如果您使用该标准,无论如何都需要准备使用列表推导式。 :) - ThorSummoner
7
反之(将整数列表转换为字符串列表):使用map(str, results)函数。 - Ali ISSA
16
可以简化这个答案:只需始终使用list(map(int, results)),它适用于任何Python版本。 - mvp
2
我只想补充一下,对于map函数,它的类型是可迭代的,因此从技术上讲,如果您要遍历它,您不需要将其转换为列表。 - ThatOneAmazingPanda

477

在列表 xs 上使用列表推导式

[int(x) for x in xs]

例如

>>> xs = ["1", "2", "3"]
>>> [int(x) for x in xs]
[1, 2, 3]

31
列表推导式也很棒。对于楼主来说,可以看看这里以获得关于map和列表推导式的清晰对比:https://dev59.com/mHM_5IYBdhLWcg3wvV5w - cheeken

9

有几种方法可以将列表中的字符串数字转换为整数。

在Python 2.x中,您可以使用map函数:

>>> results = ['1', '2', '3']
>>> results = map(int, results)
>>> results
[1, 2, 3]

这里,它返回应用函数后的元素列表。
在Python 3.x中,您可以使用相同的map
>>> results = ['1', '2', '3']
>>> results = list(map(int, results))
>>> results
[1, 2, 3]

与Python 2.x不同,这里的map函数将返回一个名为iterator的映射对象,它将逐个生成结果(值),这就是我们需要添加一个名为list的函数的原因,该函数将应用于所有可迭代项。
请参考下面的图像,了解Python 3.x中map函数的返回值及其类型。

map function iterator object and it's type

第三种方法适用于Python 2.x和Python 3.x,即列表推导式

>>> results = ['1', '2', '3']
>>> results = [int(i) for i in results]
>>> results
[1, 2, 3]

8
您可以使用Python中的循环简写轻松将字符串列表项转换为整数项。
假设您有一个字符串 result = ['1','2','3'],只需执行以下操作:
result = [int(item) for item in result]
print(result)

它会给你输出结果,例如:

[1,2,3]

1
相同的解决方案已经在上面发布过了。 - Manu mathew

8

如果您的列表只包含纯整数字符串,那么接受的答案就是正确的选择。如果您提供的东西不是整数,它将崩溃。

因此:如果您的数据可能包含整数、浮点数或其他类型的内容,您可以利用自己的带有错误处理的函数:

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

5
比列表推导稍微复杂一些,但同样有用的是:
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

2

当输入时,您可以简单地在一行中完成它。

[int(i) for i in input().split("")]

按您所需的位置进行分割。

如果要将列表转换为非列表,请在input().split("")的位置上放置您的列表名称。


2

以下是针对您问题的简单解决方案及其解释。

 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]

因此,只有当给定的字符串完全由数字组成时,我们才能将列表中的字符串项转换为整数,否则会生成错误。


0

我也想添加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]

方法二:使用列表推导式

# 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]

3
建议考虑在展示的方法中添加性能指标。比如说,哪种方法更快:列表推导式还是 map 函数?即 map。 - jtromans
所有这些方法都已经被现有答案彻底涵盖了。 - Karl Knechtel

0
以下答案,即使是最受欢迎的答案,也并不适用于所有情况。我有一个针对超级顽固推力结构的解决方案。 我有这样一件事: AA = ['0', '0.5', '0.5', '0.1', '0.1', '0.1', '0.1']
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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接