2014-03-06 45 views
2

我有一個list l=['abc','abcdef','def','defdef','polopolo'] 即時消息試圖刪除其超字符串已經在列表中的字符串。在這種情況下,結果應該是:python從字符串列表中刪除子字符串

['abcdef','defdef','polopolo']

我寫的代碼:

l=['abc','abcdef','def','defdef','polopolo'] 
res=['abc','abcdef','def','defdef','polopolo'] 
for each in l: 
    l1=[x for x in l if x!=each] 
    for other in l1: 
     if each in other: 
      res.remove(each) 

,但它似乎沒有工作。我讀過,我們無法從列表中刪除,而迭代它。因此,複製res。,而l是我的原始列表。 在此先感謝。

+1

如果你在'res.remove(each)'後立即跳出循環,你的代碼就可以工作了:)爲了一個有效的方法來做到這一點,請檢查我的答案:) – thefourtheye

+0

我現在非常愚蠢的錯誤在你解釋它。 :)謝謝 – user2058724

+0

不客氣;) – thefourtheye

回答

3
l=['abc','abcdef','def','defdef','polopolo'] 
print [j for i, j in enumerate(l) if all(j not in k for k in l[i + 1:])] 
# ['abcdef', 'defdef', 'polopolo'] 

我們之前

l = sorted(l, key = len) 
print [j for i, j in enumerate(l) if all(j not in k for k in l[i + 1:])] 

由於@Ashwini Chaudhary mentions in the comments加速它的一個非常小的,通過排序列表,如果你想保留重複的字符串,那麼你就可以做到這一點

l = ['abc','defghi' 'abcdef','def','defdef','defdef', 'polopolo'] 
l = sorted(l, key = len) 
print [j for i,j in enumerate(l) if all(j == k or (j not in k) for k in l[i+1:])] 
# ['defdef', 'defdef', 'polopolo', 'defghiabcdef'] 
+0

嘗試用'['abc','defghi''abcdef','def','defdef','defdef','polopolo']' –

+0

@AshwiniChaudhary我得到' 'defghiabcdef','defdef','polopolo']'。那是錯的嗎? – thefourtheye

+0

杜!在'defghi'之後錯過了','BTW'defdef'計數減少到1. –

相關問題