从元组列表中删除重复的成员 [英] Removing duplicates members from a list of tuples

查看:143
本文介绍了从元组列表中删除重复的成员的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这个问题在SO中可能有类似之处,但我的情况有所不同。我试图将这些答案改为我的问题,但不能。
所以这里是这样的东西:
我有这个列表:



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



我想通过保留与它相关联的更大数量的元组来删除此列表中的重复项。所以列表应该如下所示:



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



任何人都可以帮我吗?内部列表中的项目顺序非常重要。
谢谢

解决方案

 >>> lst = [(['c','a','b'],10),(['c','a','b'],9),(['h','b' 2)] 
>>> from collections import defaultdict
>>>> d = defaultdict(int)
>>>对于i,j在lst中:
d [tuple(i)] = max(d [tuple(i)],j)#假设正数


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


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

解决方案

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

这篇关于从元组列表中删除重复的成员的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆