我有一个源代码列表,通过它可以找到匹配的字符串,并返回列表中的所有匹配项。问题是,每次没有找到匹配项时,我都会得到一个空list元素。
例如:“火柴”、“火柴”、“火柴二”、……
代码如下所示:
name_match = re.compile("\s\w+\(")
match_list = []
match_list_reformat = []
for x in range(0,30):
if name_match.findall(source_code[x]) != None:
match_list.append(gc_name_match.findall(source_code[x]))
format = "".join([c for c in match_list[x] if c is not '(']).replace("(", "")
match_list_reformat.append(format)
return match_list_reformat使用"if name_match.findall(source_codex) != None:“不会改变结果。
旁白。如何使用这个def遍历源代码的所有行?范围(0,30)只是一个解决方案。
发布于 2018-11-02 15:25:47
只需对for循环中的最后一行进行一个小小的更改。
match_list_reformat.append(format) if format != '' else False若要遍历所有源代码,请将range(30)更改为range(len(source_code))
发布于 2018-11-02 15:23:53
最简单的没有re,因为Python3从过滤器返回一个迭代器,所以应该在调用list()时包装
>>> mylst
['matchone', '', 'matchtwo', '', 'matchall', '']
>>> list(filter(None, mylst))
['matchone', 'matchtwo', 'matchall']过滤器是最快的。
来自文档的:
filter( function,iterable)从可迭代元素中构造一个迭代器,其中函数返回true。迭代可以是序列、支持迭代的容器,也可以是迭代器。如果函数为None,则假定为恒等函数,即删除所有可迭代的false元素。 请注意,如果函数不是None,则过滤器( function,iterable)等效于生成器表达式(如果函数( item )中项的项为item ),如果函数为None,则等价于生成器表达式(item )。
https://stackoverflow.com/questions/53121303
复制相似问题