如何从字符串列表或混合列表中提取整数(不使用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
相关产品推荐
相关产品推荐

