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

Mic*_*ael 542 python int list

在Python中,我想将列表中的所有字符串转换为整数.

所以,如果我有:

results = ['1', '2', '3']
Run Code Online (Sandbox Code Playgroud)

我该怎么做:

results = [1, 2, 3]
Run Code Online (Sandbox Code Playgroud)

che*_*ken 1075

使用该map函数(在Python 2.x中):

results = map(int, results)
Run Code Online (Sandbox Code Playgroud)

在Python 3中,您需要将结果转换map为列表:

results = list(map(int, results))
Run Code Online (Sandbox Code Playgroud)

  • 我想指出pylint不鼓励使用`map`,所以如果你曾经使用过那个标准,那么准备使用列表推导.:) (21认同)
  • 你可以简化这个答案:只使用`list(map(int,results))`,它适用于任何Python版本. (10认同)
  • 逆是(将int的列表转换为字符串列表):map(str,results) (4认同)
  • 我只想为地图函数添加它的类型是可迭代的,因此从技术上讲,如果您要迭代它,则不需要将其转换为列表。 (2认同)

Chr*_*Vig 352

使用列表理解:

results = [int(i) for i in results]
Run Code Online (Sandbox Code Playgroud)

例如

>>> results = ["1", "2", "3"]
>>> results = [int(i) for i in results]
>>> results
[1, 2, 3]
Run Code Online (Sandbox Code Playgroud)

  • 列表理解也很棒.到OP - 看这里是为了看到地图和列表理解的良好对比:http://stackoverflow.com/questions/1247486/python-list-comprehension-vs-map (30认同)

Shu*_*pta 11

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

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

>>> results = ['1', '2', '3']
>>> results = map(int, results)
>>> results
[1, 2, 3]
Run Code Online (Sandbox Code Playgroud)

在这里,它返回应用该函数后的元素列表。

在 Python 3.x 中,您可以使用相同的映射

>>> results = ['1', '2', '3']
>>> results = list(map(int, results))
>>> results
[1, 2, 3]
Run Code Online (Sandbox Code Playgroud)

与python 2.x不同,这里的map函数将返回map对象,即iterator它将一一产生结果(值),这就是我们进一步需要添加一个名为as的函数的原因list,它将应用于所有可迭代项。

函数的返回值map及其类型(Python 3.x 的情况下)请参考下图

映射函数迭代器对象及其类型

第三种方法对于 python 2.x 和 python 3.x 都很常见,即列表推导式

>>> results = ['1', '2', '3']
>>> results = [int(i) for i in results]
>>> results
[1, 2, 3]
Run Code Online (Sandbox Code Playgroud)


Pat*_*ner 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)
Run Code Online (Sandbox Code Playgroud)

输出:

['unkind', 'data', 42, 98, 47.11, 'of mixed', 'types']
Run Code Online (Sandbox Code Playgroud)

要在可迭代对象中处理可迭代对象,您可以使用此帮助器:

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)
Run Code Online (Sandbox Code Playgroud)

输出:

['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
Run Code Online (Sandbox Code Playgroud)


小智 8

您可以使用Python中的循环简写轻松将字符串列表项转换为整数项

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

做就是了,

result = [int(item) for item in result]
print(result)
Run Code Online (Sandbox Code Playgroud)

它会给你输出像

[1,2,3]
Run Code Online (Sandbox Code Playgroud)


小智 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)
Run Code Online (Sandbox Code Playgroud)

例如

>>> results = ["1", "2", "3"]
>>> str_list_to_int_list(results)
[1, 2, 3]
Run Code Online (Sandbox Code Playgroud)

还:

def str_list_to_int_list(str_list):
    int_list = [int(n) for n in str_list]
    return int_list
Run Code Online (Sandbox Code Playgroud)