Removing duplicates members from a list of tuples

我怕爱的太早我们不能终老 提交于 2019-12-08 11:27:59

问题


this question might have similars in SO but my case is a bit different. and I tried to adapt those answers to my problem but couldn't. so here is the thing: I have this list :

[(['c', 'a', 'b'], 10), (['c', 'a', 'b'], 9),(['h','b'],2)] for example.

I want to remove the duplicates in this list by keeping tuple that has the larger number associated with it. so the list should look like this:

[(['c', 'a', 'b'], 10),(['h','b'],2)]

can anyone help me? the order of the items inside the inner lists is very important. thanks


回答1:


>>> lst = [(['c', 'a', 'b'], 10), (['c', 'a', 'b'], 9),(['h','b'],2)]
>>> from collections import defaultdict
>>> d = defaultdict(int)
>>> for i, j in lst:
    d[tuple(i)] = max(d[tuple(i)], j)          # assuming positive numbers


>>> d
defaultdict(<class 'int'>, {('h', 'b'): 2, ('c', 'a', 'b'): 10})



回答2:


If, as your example suggests, the items are already sorted by the numbers (in your case reverse), you can do:

d = dict(reversed(lst))
list(d.iteritems())

The default behavior of the dict() function is that the last seen value for the key is stored. So if they are sorted in reverse order, the last seen value when iterating in reverse order will be the largest. Otherwise, use @SilentGhost`s answer.



来源:https://stackoverflow.com/questions/4009304/removing-duplicates-members-from-a-list-of-tuples

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!