Python实现从嵌套列表中移除纯整数字符串的问题
问题:过滤嵌套列表,移除纯整数字符串,保留含$、+、-的字符串
我需要从嵌套列表中移除仅包含整数的字符串,保留所有带有$、+或-符号的字符串。以下是原始数据与期望输出:
string = (",A', B', C', +145', $50', Split', D', E', F', 1', 2000', -678', $10', Split', H', I', J', 3', 4', 50', +132', $45', Split'").replace("'", '') ls_of_lists = [x.split(",") for x in string.split('Split')] # 期望输出: desired_ls_of_ls = [ ["A", "B", "C", "+145", "$50"], ["D", "E", "F", "-678", "$10"], ["H", "I", "J", "+132","$45"] ]
我尝试了多个过滤函数,但均未得到预期结果:
def int_filter_0( someList ): for v in someList: try: int(v) continue # Skip these except ValueError: yield v # Keep these def int_filter_1(some_list): for v in some_list: if v.find("\\+"): yield v # Keep these if v.find("\\-&"): yield v # Keep these else: try: int(v) continue # Skip these except ValueError: yield v # Keep these def int_filter_2(some_list): for v in some_list: if v.contains("\\+"): yield v # Keep these if v.contains("\\-&"): yield v # Keep these else: try: int(v) continue # Skip these except ValueError: yield v # Keep these def int_filter_3( someList ): for v in someList: try: if v.find("\\+"): continue if v.find("\\-&"): continue int(v) continue # Skip these except ValueError: yield v # Keep these test_0 = [list(int_filter_0(item)) for item in ls_of_lists] test_1 = [list(int_filter_1(item)) for item in ls_of_lists] test_2 = [list(int_filter_2(item)) for item in ls_of_lists] test_3 = [list(int_filter_3(item)) for item in ls_of_lists]
问题分析
你之前的过滤函数存在几个关键问题:
- int_filter_0:
int("+145")和int("-678")都能成功转换为整数,导致这些需要保留的带符号数字被错误跳过。 - int_filter_1/3:使用
find("\\+")多了一个反斜杠,且find()返回-1表示未找到,逻辑完全搞反;同时\\-&是错误写法,连字符不需要转义。 - int_filter_2:Python字符串没有
contains()方法,应该用in或者find()判断子串是否存在。
正确解决方案
核心思路:先清理每个元素的空格和空字符串,再判断元素是否为纯数字字符串(仅包含0-9),是则移除,否则保留。
def filter_valid_items(some_list): cleaned = [v.strip() for v in some_list if v.strip()] # 移除空字符串并清理空格 for item in cleaned: # 判断是否为纯数字字符串(不含$、+、-) if item.isdigit(): continue # 保留其他所有元素(包括带$、+、-的数字和普通字符串) yield item # 生成最终结果 result = [list(filter_valid_items(sublist)) for sublist in ls_of_lists] print(result)
运行结果与期望输出完全一致:
[['A', 'B', 'C', '+145', '$50'], ['D', 'E', 'F', '-678', '$10'], ['H', 'I', 'J', '+132', '$45']]
内容的提问来源于stack exchange,提问作者Fugles
相关产品推荐
相关产品推荐

