2017-02-18 137 views
3

如果我有一个Python列表:Python的列表中移除元素

text = ["the", "red", "", "", "fox", "", "is"] 

如何使用itertools(或其他方式),这样它会检查elemelem+1修改文本列表,如果发现等于"" ,然后将它们从列表中删除。如果找到elem + elemt1(因此["fox" "", "is"]部分保留在列表中),我只想修改列表。列表元素的排序必须保持不变。

text = ["the", "red", "fox", "", "is"] 
+0

所以你想用“删除空值”从工作清单? –

+2

'[“the”,“red”,“”,“”,“”,“fox”,“”,“是”]是什么?是否所有三个空弦都被删除,或者你保留其中一个? – Psidom

回答

2
from itertools import groupby, chain 

print list(chain(*[ 
    l for l in [list(it) for _, it in groupby(text)] if l[:2] != ['', ''] 
])) 

结果:

['the', 'red', 'fox', '', 'is'] 

随着groupby我们同样可以连续元素的列表。然后我们检查每个列表是否长度大于2,所有元素都是空字符串。然后我们保留我们想要的,并使用chain将列表弄平。

+0

使用'zip_longest' – Daniel

+0

该结果在该问题中看起来不像所期望的结果。 – schwobaseggl

+0

你说得对。我更新了我的答案 – JuniorCompressor

-3
for t in text: 
    if not t: 
    text.remove(t) 
+1

永不改变你正在迭代的列表。 – Daniel

2

您可以使用itertools.groupby:更高效的

import itertools 

new = [] 
for item, group in itertools.groupby(text): 
    group = list(group) 
    if item != '' or len(group) == 1: 
     new.extend(group) 

>>> new 
['the', 'red', 'fox', '', 'is'] 

还是有点用groupby - 功能。人们可以使用空字符串被认为False转换为bool当事实:

import itertools 

new = [] 
for item, group in itertools.groupby(text, bool): 
    group = list(group) 
    if item or len(group) == 1: 
     new.extend(group) 

>>> new 
['the', 'red', 'fox', '', 'is'] 
+0

这与我的解决方案相同,但更具可读性,因此具有启发性;) – schwobaseggl

0

它拥有超过2个空格也

text = ["the", "red", "","", "", "fox", "", "is"] 
new_text = [] 

text_len = len(text); 
print(text_len) 
i = 0; 
while(i < text_len): 
    if (text[i] == "" and text[i + 1] == ""): 
     i += 1; 
     while(True): 
       if (text[i] == "" and text[i + 1] == ""): 
        i+=1; 
       else: 
         break; 

    else : 
     new_text.append(text[i]); 
    i += 1; 
print(new_text)