Python 查找字符串列表中的所有整数并以列表的形式输出

Python 查找字符串列表中的所有整数并以列表的形式输出,python,python-3.x,list,Python,Python 3.x,List,如何从字符串和整数的列表中查找和提取整数(不使用re模块) ['My', '2', 'favorite', 'numbers', 'are', '42', 'and', '69'] 如何以列表的形式提取所有的整数(2,42,69)? 所需输出: [2, 42, 69] 一个快速解决方案是尝试将项目强制转换为int,并保留成功的项目 任何类型的列表: 字符串列表 如Mateen Ulhaq所述,如果您的输入总是string类型,则更适合使用: [int(s) for s in my_list

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

['My', '2', 'favorite', 'numbers', 'are', '42', 'and', '69']
如何以列表的形式提取所有的整数(2,42,69)? 所需输出:

[2, 42, 69]

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

任何类型的列表: 字符串列表 如
Mateen Ulhaq
所述,如果您的输入总是
string
类型,则更适合使用:

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

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

,则此解决方案将不起作用。您可以通过迭代列表的每个元素并尝试将其转换为整数来完成此操作。如果转换成功,则将其附加到整数列表中

a = ['My', '2', 'favorite', 'numbers', 'are', '42', 'and', '69']
ints = []
for i in a:
    try:
        z = int(i)
        ints.append(z)
    except:
        pass
或者你也可以选择一艘来自:


当然,我们应该避免这种解决方案,因为异常是昂贵的。哦,这是真的!刚刚看到您的评论,如果我们希望它们都是字符串,那么这是一个很好的解决方案。
[int(s)for s in my_list if s.isdigit()]
a = ['My', '2', 'favorite', 'numbers', 'are', '42', 'and', '69']
ints = []
for i in a:
    try:
        z = int(i)
        ints.append(z)
    except:
        pass
a = ['My', '2', 'favorite', 'numbers', 'are', '42', 'and', '69']
[int(s) for s in a if s.isdigit()]
#[2, 42, 69]