开发者

Removing duplicates members from a list of tuples

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开发者_StackOverflow中文版 lists is very important. thanks


>>> 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})


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜