删除空列表元素

2024-04-25 04:34:19 发布

您现在位置:Python中文网/ 问答频道 /正文

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

例如:[“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”_匹配.findall(源代码[x])!=无:“不改变结果。你知道吗

在旁注上。如何使用这个def遍历源代码的所有行?范围(0,30)只是一个解决方法。你知道吗


Tags: 字符串nameinformatsource列表forif
2条回答

对for循环中的最后一行只做一个小改动

match_list_reformat.append(format) if format != '' else False

要浏览所有源代码,请将range(30)更改为range(len(source_code))

最简单的没有re,因为python3从filter返回一个迭代器,所以应该包装在对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.

相关问题 更多 >