我有一個源代碼列表,正在查看它以查找匹配的字符串并返回列表中的所有匹配項。問題是每次找不到匹配項時我都會得到一個空列表元素。例如: ["matchone","",matchtwo"", .....]代碼如下所示: 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_code[x]) != None:”不會改變結(jié)果。在旁注。我怎樣才能用這個 def 瀏覽源代碼的所有行?range(0,30) 只是一種解決方法。
2 回答

慕慕森
TA貢獻1856條經(jīng)驗 獲得超17個贊
最簡單的沒有re,因為 Python 3 從過濾器返回一個迭代器,所以應(yīng)該包裝在對list()
>>> mylst
['matchone', '', 'matchtwo', '', 'matchall', '']
>>> list(filter(None, mylst))
['matchone', 'matchtwo', 'matchall']
過濾 速度最快。
從文件:
filter(function, iterable) 從那些函數(shù)返回 true 的 iterable 元素構(gòu)造一個迭代器。iterable 可以是一個序列、一個支持迭代的容器或一個迭代器。如果 function 為 None,則假定恒等函數(shù),即刪除所有為 false 的 iterable 元素。
注意 filter(function, iterable) 等價于生成器表達式(item for item in iterable if function(item)) if function is not None and (item for item in iterable if item) if function is None。
添加回答
舉報
0/150
提交
取消