【问题标题】:How to convert integers in a list to int()?如何将列表中的整数转换为 int()?
【发布时间】:2019-10-06 23:23:27
【问题描述】:

我正在制作一个计算字符串中数学的函数。首先,它获取字符串,然后将其转换为列表。

我尝试将整个数组转换为整数数组,但当数组如下所示时遇到错误:["hello",1,"*",2] 因为一切都不是数字。

我只想将数组["1","2","hello","3"]中的整数转换为整数,所以数组变成[1,2,"hello",3]

这样,当我这样做时,我可以对整数进行数学运算,而不是像目前那样将它们视为字符串:

1 + 2

我得到12 作为输出。 我想要3 作为输出。

【问题讨论】:

标签: python string list math int


【解决方案1】:

您可以将list comprehensionstr.isdigit()int() 一起使用:

ls = ["1", "2", "hello", "3"]
new_ls = [int(n) if n.isdigit() else n for n in ls]
print(new_ls)

输出:

[1, 2, 'hello', 3]

 

您还可以添加str.lstrip() 使其适用于负数:

ls = ["1", "-2", "hello", "-3"]
new_ls = [int(n) if n.lstrip('-').isdigit() else n for n in ls]
print(new_ls)

输出:

[1, -2, 'hello', -3]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-12-27
    • 2013-08-25
    • 1970-01-01
    • 1970-01-01
    • 2016-12-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多