微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

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

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

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的评论

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。