从Python中的列表中删除重复项很容易(保留顺序):
def removeDuplicates(sequence):
checked = []
for element in sequence:
if element not in checked:
checked.append(element)
return checked
但是如果我想删除删除重复项的最后一个实例(即:[1,1,1,2,2,2] -> [1,1,2,2]
),我该怎么办?
答案 0 :(得分:2)
1 - 遍历列表,并将每个元素添加到字典中,我们称之为duplicateMap
。
Key: element in the list
Value: count of element
2 - 从后面再次遍历列表。
对于每个元素,请检查
1) if duplicateMap contains the element;
2) if the count is greater than 1.
如果是,
1) remove the element from the list;
2) remove the element from duplicateMap.
答案 1 :(得分:1)
怎么样:
from collections import OrderedDict
from itertools import chain
data = [
['Jim', 18],
['James', 19],
['Bob', 20],
['Jim', 15],
['Bob', 55],
['Jim', 99],
['Single', 123]
]
od = OrderedDict()
for el in data:
od.setdefault(el[0], []).append(el)
deduped = list(chain.from_iterable(item[:-1] if len(item) > 1 else item for item in od.itervalues()))
# [['Jim', 18], ['Jim', 15], ['James', 19], ['Bob', 20], ['Single', 123]]
这使用名称和年龄作为示例数据和基于名称的重复数据删除 - 这比仅仅数字更有趣......我们将它们追加到每个列表中,最后将所有元素放入并将它们放回所呈现的密钥的顺序组合在一起。
答案 2 :(得分:1)
我的python不太好但是怎么样:
>>> l = [1,1,1,2,2,2]
>>> last_occ=[len(l) - 1 - l[::-1].index(i) for i in set(l)] # Find position of each last occurence
>>> for pos in last_occ[::-1]: # Reverse the occurrence list otherwise you may get an IndexError
l.pop(pos)
>>> l
[1, 1, 2, 2]
答案 3 :(得分:1)
这样怎么样
def removelastduplicate(s):
len_s=len(s)
checked=[]
for i in range(0,len_s):
number=s.pop(0)
if number in s: # the last occurance wont be present in the list, so not added
checked.append(number)
return checked
s=[1,1,1,2,2,2]
print removelastduplicate(s)
答案 4 :(得分:0)
好的,我的思维现在处于Javascript模式,所以代码并不是我的头脑,但从概念上讲,我首先想到的是:
for x in originalList of [A,A,B,B,A,B,C,C]
store x as entry in dictionary {A:[0,1,4];B:[2,3,5];C:[6,7]}
Then loop through all of the lists in the dictionary and pull the max value
from each and push it to a new list that you then reverse sort,
ex output [7,5,4]
Then for each value in the resulting list, remove the value at that place in the original list
(Do it in the largest to least order though, that way as you remove values, its not changing the value of the other entries that need to be removed)
可能有更好的方法来做到这一点,对不起,我没有为你提供这个想法的代码,但我希望这个概念有所帮助,如果你需要我进一步解释我的意思,请告诉我。