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

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

当前回答

如果您的列表包含纯整数字符串,接受的答案是要走的路。如果输入的不是整数它就会崩溃。

所以:如果你的数据可能包含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

其他回答

下面的答案,即使是最流行的答案,也并非适用于所有情况。我有这样一个解决方案的超级抗推力str。 我有这样一件事:

AA =[’0’、160。5,160。5、160。1、160。1、160。1,1 160。]

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]

你可以笑,但这很有效。

这里有一个简单的解决方案,对您的查询进行了解释。

 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]

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

如果您的列表包含纯整数字符串,接受的答案是要走的路。如果输入的不是整数它就会崩溃。

所以:如果你的数据可能包含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]

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

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