You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何从字符串列表或混合列表中提取整数(不使用re模块)

问题2:从给定混合列表中提取整数(不使用re模块)

For your specific list ['My', '2', 'favorite', 'numbers', 'are', '42', 'and', '69'], we can use the same logic as above—no need for regex at all. Here's the direct implementation:

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

for item in mixed_list:
    try:
        result.append(int(item))
    except ValueError:
        # Ignore non-integer strings
        pass

print(result)  # Output: [2, 42, 69]

This is straightforward and efficient for this use case. The try-except block is perfect here because we only care about strings that are pure integers—no partial matches or edge cases to worry about in this specific list.


内容的提问来源于stack exchange,提问作者Naf

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 08:44:53