如何从另一个列表中删除空列表?

问题描述

在通过此代码运行文本之后:

import re


def text_manipulator(text):
    paras = re.split('\n|\n ',text)
    item_number = 0
    for item in paras:
        item_replace = re.split('(?<=[.!?]) +',item)
        paras[item_number] = item_replace
        item_number += 1
    fixed_paras = [x for x in paras if x]
    return fixed_paras

我剩下这个了。

[["Not a postal worker,but I'm good friends with the one on my route,"],[''],['He has helped me through some tough times (just a nice guy to talk to)'],['I often offer him a cold gallon of water or a energy drink,he seems to really enjoy.','He is a real down to earth guy.']]

该如何处理?

[["Not a postal worker,'He is a real down to earth guy.']]

预先感谢

解决方法

根据any(iterable)的文档:

如果iterable的任何元素为true,则返回True。如果iterable为空,则返回False

因此,当将字符串列表传递给Any时,如果列表中的所有元素都是空字符串,则它将返回False,因为Empty String等效于False。 / p>

因此,在您的代码中,将第二行替换为:

fixed_paras = [x for x in paras if any(x)]

也将删除具有空字符串的列表。

注意:该答案基于juanpa.arrivillaga的评论