Skip to main content
 首页 » 编程设计

python之删除空列表元素

2025年05月04日20telwanggs

我有一个源代码列表,正在查看这些源代码以找到匹配的字符串并返回列表中的所有匹配项。 问题是每次找不到匹配项时我都会得到一个空列表元素。

例如:["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:”不会改变结果。

旁注。我如何使用此 def 遍历源代码的所有行? range(0,30) 只是一种解决方法。

请您参考如下方法:

没有 re 最简单,因为 Python 3 从过滤器返回一个迭代器,所以应该包含在对 list() 的调用中

>>> mylst 
['matchone', '', 'matchtwo', '', 'matchall', ''] 
 
>>> list(filter(None, mylst)) 
['matchone', 'matchtwo', 'matchall'] 

filter最快。

来自文档:

filter(function, iterable) Construct an iterator from those elements of iterable for which function returns true. iterable may be either a sequence, a container which supports iteration, or an iterator. If function is None, the identity function is assumed, that is, all elements of iterable that are false are removed.

Note that filter(function, iterable) is equivalent to the generator expression (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.