从元组列表中删除重复的成员

发布于 2024-09-28 12:54:26 字数 304 浏览 2 评论 0原文

这个问题可能与SO有相似之处,但我的情况有点不同。我尝试根据我的问题调整这些答案,但失败了。 所以事情是这样的: 我有这个列表:

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

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

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

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

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

┼── 2024-10-05 12:54:26
>>> 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})
>>> 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})
欲拥i 2024-10-05 12:54:26

如果,正如您的示例所示,项目已经按数字排序(在您的情况下相反),您可以执行以下操作:

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

dict() 函数的默认行为是最后看到的值密钥已存储。因此,如果它们按逆序排序,则逆序迭代时最后看到的值将是最大的。否则,请使用@SilentGhost的答案

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文