2017-02-18 145 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)