gpt4 book ai didi

python - 查找字符串列表中的所有整数并将其以列表的形式输出

转载 作者:太空宇宙 更新时间:2023-11-03 14:13:21 25 4
gpt4 key购买 nike

如何从列表查找提取整数(不使用re模块) strong>字符串和整数

['My', '2', 'favorite', 'numbers', 'are', '42', 'and', '69']

如何以列表的形式提取所有整数(2,42,69)?所需输出:

[2, 42, 69]

最佳答案

一个快速的解决方案是尝试将项目转换为 int 并保留那些成功的项目。

任何类型的列表:

result = []
for i in x:
try:
result.append(int(i))
except Exception:
pass

print(result)
>>[2, 42, 69]

字符串列表

正如Mateen Ulhaq提到的,如果你的输入始终是string类型,那么使用:

[int(s) for s in my_list if s.isdigit()]

注意:如果您的字符串包含负数,例如 '-12'

,则此解决方案将不起作用

关于python - 查找字符串列表中的所有整数并将其以列表的形式输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48353281/

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