gpt4 book ai didi

python - 如何将列表中的整数转换为 int()?

转载 作者:行者123 更新时间:2023-12-01 07:50:51 25 4
gpt4 key购买 nike

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

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

我只想将数组 ["1","2","hello","3"] 中的整数转换为整数,因此数组变为 [1, 2,"你好",3]

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

1 + 2

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

最佳答案

您可以使用 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)

Output:

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

Output:

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

关于python - 如何将列表中的整数转换为 int()?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56223490/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com