Python在维持秩序的同时从列表中删除一些重复项?
我想删除我的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]
因此,不维护订单。
任何想法,将不胜感激!谢谢!
不能完全肯定,如果c
和f
是特殊情况,或者如果您只想压缩连续的重复。如果是后者,你可以使用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']
谢谢!有效! – user1530318 2012-07-23 15:40:45
若要从列表中删除连续的重复,你可以使用下面的发生器功能:
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']
谢谢你的回答! – user1530318 2012-07-23 15:40:39
如果你想忽略某些项目中删除时重复...
list2 = []
for item in list1:
if item not in list2 or item in ('c','f'):
list2.append(item)
编辑:请注意,这不会删除连续的项目
这似乎没有给出样本输入'list1'所需的'wantedList'值。 – 2012-07-23 03:39:56
你是对的!他想要连续的'f'和'c'保存...问题需要更加具体(而且我需要更轻松) – SudoNhim 2012-07-23 03:45:26
编辑 没关系,我看错了你的问题。我以为你只想保持一定数量的双打。
我会推荐这样的东西。它允许一般形式保留一定的双打。
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)
简单的解决方案是该元素比较到下一个或前一个元素
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
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)。
- 如果'temp_list'为空,请添加该项目。
- 如果不是,请检查temp_list中的最后一项是否为 ,与我们从“list1”中取出的项目是否相同。
- 如果项目不同,则追加到temp_list中。
准确地说,你想删除*连续*重复?还是有什么特别的'c'和'f'使得它们与其他元素的区别对待? – 2012-07-23 03:28:30