繁体   English   中英

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

[英]Convert all strings in a list to int

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

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

鉴于:

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

在 Python 2 中,使用map获取整数列表:

map(int, xs)

在 Python 3 中,在map之后应用list以获得整数列表:

list(map(int, xs))

在列表xs上使用列表xs

[int(x) for x in xs]

例如

>>> xs = ["1", "2", "3"]
>>> [int(x) for x in xs]
[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

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

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

做就是了,

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

它会给你像这样的输出

[1,2,3]

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

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

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

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

在 Python 3.x 中,您可以使用相同的地图

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

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

map函数的返回值和python 3.x的类型见下图

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

python 2.x 和 python 3.x 通用的第三种方法,即List Comprehensions

>>> results = ['1', '2', '3']
>>> results = [int(i) for i in results]
>>> results
[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)

例如

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

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

 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(i) for i in input().split("")]

把它拆分到你想要的地方。

如果要转换列表而不是列表,只需将列表名称放在input().split("")的位置。

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

方法#2:使用列表推导

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

方法 #3:使用 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]

下面的答案,即使是最受欢迎的答案,也不适用于所有情况。 我有这样一个超抗推力 str 的解决方案。 我有这样的事情:

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]

你可以笑,但它有效。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM