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

['1', '2', '3']  ⟶  [1, 2, 3]

当前回答

考虑到:

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

使用map then list获取一个整数列表:

list(map(int, xs))

在Python 2中,list是不必要的,因为map返回一个列表:

map(int, xs)

其他回答

在获取输入时,只需在一行中完成。

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

你想在哪分就在哪分。

如果你想转换一个列表而不是列表,只需把你的列表名称放在input().split("")的位置。

比列表理解更扩展一点,但同样有用:

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,可能是浮点数或其他东西-你可以利用你自己的函数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

使用python中的循环简写,可以轻松地将字符串列表项转换为int项

假设你有一个字符串result = ['1','2','3']

就做,

result = [int(item) for item in result]
print(result)

它会给你输出

[1,2,3]

在列表xs上使用一个列表推导式:

[int(x) for x in xs]

e.g.

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