![](/img/trans.png)
[英]How can I append lists with items from another list and leave these empty in a simulation?
[英]How can I remove empty lists from within another list?
通過此代碼運行文本后:
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.']]
提前致謝
根據any(iterable)
的文檔:
如果可迭代的任何元素為真,則返回
True
。 如果可迭代對象為空,則返回False
。
因此,當將字符串列表傳遞給Any
時,如果列表中的所有元素都是空字符串,那么它將返回False
,因為 Empty String 等效於False
。
因此,在您的代碼中,將倒數第二行替換為:
fixed_paras = [x for x in paras if any(x)]
也會消除帶有空字符串的列表。
注意:此答案基於juanpa.arrivillaga的評論
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.