2012-07-23 158 views
3

我想刪除我的python列表中的某些重複項。 我知道有辦法刪除所有重複,但我想刪除連續重複,同時保持列表順序。Python在維持秩序的同時從列表中刪除一些重複項?

例如,我有一個列表,如下列:

list1 = [a,a,b,b,c,c,f,f,d,d,e,e,f,f,g,g,c,c] 

不過,我想刪除重複項,並維持秩序,但仍保持2級C的和2 F的,像這樣的:

wantedList = [a,b,c,f,d,e,f,g,c] 

到目前爲止,我有這樣的:

z = 0 
j=0 
list2=[] 
for i in list1: 
    if i == "c": 
     z = z+1 
     if (z==1): 
      list2.append(i) 
     if (z==2): 
      list2.append(i) 
     else: 
      pass 
    elif i == "f": 
     j = j+1 
     if (j==1): 
      list2.append(i) 
     if (j==2): 
      list2.append(i) 
     else: 
      pass 
    else: 
     if i not in list2: 
      list2.append(i) 

然而,這種方法讓我喜歡的事:

wantedList = [a,b,c,c,d,e,f,f,g] 

因此,不維護訂單。

任何想法,將不勝感激!謝謝!

+4

準確地說,你想刪除*連續*重複?還是有什麼特別的'c'和'f'使得它們與其他元素的區別對待? – 2012-07-23 03:28:30

回答

8

不能完全肯定,如果cf是特殊情況,或者如果您只想壓縮連續的重複。如果是後者,你可以使用itertools.groupby()

>>> import itertools 
>>> list1 
['a', 'a', 'b', 'b', 'c', 'c', 'f', 'f', 'd', 'd', 'e', 'e', 'f', 'f', 'g', 'g', 'c', 'c'] 
>>> [k for k, g in itertools.groupby(list1)] 
['a', 'b', 'c', 'f', 'd', 'e', 'f', 'g', 'c'] 
+0

謝謝!有效! – user1530318 2012-07-23 15:40:45

3

若要從列表中刪除連續的重複,你可以使用下面的發生器功能:

def remove_consecutive_duplicates(a): 
    last = None 
    for x in a: 
     if x != last: 
      yield x 
     last = x 

與您的數據,這給:

>>> list1 = ['a','a','b','b','c','c','f','f','d','d','e','e','f','f','g','g','c','c'] 
>>> list(remove_consecutive_duplicates(list1)) 
['a', 'b', 'c', 'f', 'd', 'e', 'f', 'g', 'c'] 
+0

謝謝你的回答! – user1530318 2012-07-23 15:40:39

0

如果你想忽略某些項目中刪除時重複...

list2 = [] 
for item in list1: 
    if item not in list2 or item in ('c','f'): 
     list2.append(item) 

編輯:請注意,這不會刪除連續的項目

+0

這似乎沒有給出樣本輸入'list1'所需的'wantedList'值。 – 2012-07-23 03:39:56

+0

你是對的!他想要連續的'f'和'c'保存...問題需要更加具體(而且我需要更輕鬆) – SudoNhim 2012-07-23 03:45:26

0

編輯 沒關係,我看錯了你的問題。我以爲你只想保持一定數量的雙打。

我會推薦這樣的東西。它允許一般形式保留一定的雙打。

list1 = ['a','a','b','b','c','c','f','f','d','d','e','e','f','f','g','g','c','c'] 
doubleslist = ['c', 'f'] 

def remove_duplicate(firstlist, doubles): 
    newlist = [] 
    for x in firstlist: 
     if x not in newlist: 
      newlist.append(x) 
     elif x in doubles: 
      newlist.append(x) 
      doubles.remove(x) 
    return newlist 

print remove_duplicate(list1, doubleslist) 
0

簡單的解決方案是該元素比較到下一個或前一個元素

a=1 
b=2 
c=3 
d=4 
e=5 
f=6 
g=7 
list1 = [a,a,b,b,c,c,f,f,d,d,e,e,f,f,g,g,c,c] 
output_list=[list1[0]] 
for ctr in range(1, len(list1)): 
    if list1[ctr] != list1[ctr-1]: 
     output_list.append(list1[ctr]) 
print output_list 
0
list1 = ['a', 'a', 'b', 'b', 'c', 'c', 'f', 'f', 'd', 'd', 'e', 'e', 'f', 'f', 'g', 'g', 'c', 'c'] 

wantedList = [] 

for item in list1: 
    if len(wantedList) == 0: 
     wantedList.append(item) 

    elif len(wantedList) > 0: 
     if wantedList[-1] != item: 
      wantedList.append(item) 

print(wantedList) 
  1. 從主取每個項目列表(列表1)。
  2. 如果'temp_list'爲空,請添加該項目。
  3. 如果不是,請檢查temp_list中的最後一項是否爲 ,與我們從「list1」中取出的項目是否相同。
  4. 如果項目不同,則追加到temp_list中。
相關問題