【问题标题】:How can I remove empty lists from within another list?如何从另一个列表中删除空列表?
【发布时间】:2020-08-19 05:10:51
【问题描述】:

通过此代码运行文本后:

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, 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.']]

提前致谢

【问题讨论】:

  • 该列表不为空。但是,其中的项目是空的。所以[x for x in paras if any(x)] 可以工作,注意,也会过滤类似['','']
  • @juanpa.arrivillaga 非常感谢您的帮助!你介意解释一下这段代码是如何工作的吗?如果你有时间,干杯

标签: python list reddit editing python-re


【解决方案1】:

根据any(iterable) 的文档:

如果可迭代的任何元素为真,则返回True。如果可迭代对象为空,则返回False。

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

所以在您的代码中,将倒数第二行替换为:

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

也会消除带有空字符串的列表。

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-15
    • 2016-09-08
    • 2013-09-20
    • 2016-11-06
    • 1970-01-01
    相关资源
    最近更新 更多