如何从Python列表中提取字符串格式的纯整数?
解决从嵌套字符串列表中提取整数字符串的问题
没问题,我来帮你搞定这个需求!你需要从嵌套列表的每个子列表里,只保留那些是整数形式的字符串(排除浮点数和非数字字符串),下面给你两种实用的解决方案:
方法一:使用try-except块(通用且稳妥)
这种方法能处理所有可解析为整数的字符串,包括带正负号的情况(比如'-123'、'+456'),同时会自动排除浮点数字符串(比如'3.14')和非数字字符串。
代码实现
# 原始列表 list_1 = [['50', 'ALA', 'A', '53', '5', '4'], ['55', 'GLY', 'A', '60', '1', '6'], ['67', 'ILE', 'A', '71', '5', '5']] def filter_integer_strings(nested_list): filtered_result = [] # 遍历每个子列表 for sublist in nested_list: current_filtered = [] for item in sublist: try: # 尝试将字符串转为整数,成功则保留原字符串 int(item) current_filtered.append(item) except ValueError: # 转换失败说明不是整数字符串,跳过 continue filtered_result.append(current_filtered) return filtered_result # 调用函数得到结果 processed_list = filter_integer_strings(list_1) print(processed_list)
输出结果
[['50', '53', '5', '4'], ['55', '60', '1', '6'], ['67', '71', '5', '5']]
方法二:使用str.isdigit()(简洁高效,适用于正整数场景)
如果你的列表里只有正整数形式的字符串,可以用更简洁的列表推导式结合str.isdigit()方法,它会直接判断字符串是否由纯数字组成。
代码实现
list_1 = [['50', 'ALA', 'A', '53', '5', '4'], ['55', 'GLY', 'A', '60', '1', '6'], ['67', 'ILE', 'A', '71', '5', '5']] # 嵌套列表推导式一步完成过滤 processed_list = [[item for item in sublist if item.isdigit()] for sublist in list_1] print(processed_list)
注意点
这个方法的局限性是:无法识别带正负号的整数字符串(比如'-50'会被误认为非数字),但完全匹配你给出的示例场景。
内容的提问来源于stack exchange,提问作者Stennis
相关产品推荐
相关产品推荐

