1

在 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],我该怎么做?

4

5 回答 5

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.
于 2013-10-16T20:03:58.490 回答
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]]

这使用名称和年龄作为示例数据和基于名称的重复数据删除 - 这比数字更有趣......我们将它们分别附加到一个列表中,最后获取所有元素并将它们放回呈现的顺序键组合在一起。

于 2013-10-16T20:04:47.323 回答
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]
于 2013-10-16T20:08:41.883 回答
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)
于 2013-10-16T20:10:38.677 回答
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)

可能有更好的方法可以做到这一点,很抱歉,我没有为您提供该想法的代码,但我希望这个概念有所帮助,如果您需要我进一步解释我的意思,请让我知道。

于 2013-10-16T20:04:32.637 回答