从 python 集合中获取唯一的元组 [英] Getting unique tuples out of a python set

查看:46
本文介绍了从 python 集合中获取唯一的元组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前有一套如下:

{(a,b), (b,a), (c,b), (b,c)}

我想要的是:

{(a,b), (c,b)}

您可能会注意到重复值已被完全删除,因此无论顺序如何,两个元组中都不会包含相同的元素.

如何让集合忽略元组中元素的顺序,只检查元组之间的值?

解决方案

好的,你有一个 {c1, c2, c3, ...} 集合,其中每个 cN 本身就是某种集合.

如果你不关心 cN 中元素的顺序,但关心它是唯一的(无视顺序),那么 cN 应该是一个 frozenset1 而不是 tuple:

<预><代码>>>>orig = {("a", "b"), ("b", "a"), ("c", "b"), ("b", "c")}>>>uniq = {frozenset(c) for c in orig}>>>优衣库{冻结集(['b','a']),冻结集(['b','c'])}

作为一般规则,从 Python 提供的数据类型中选择合适的数据类型将比定义和维护自定义类更直接.

<小时>

1 不能是 set,因为作为更大的 set 的成员,它需要是可哈希的.

I currently have a set like the following:

{(a,b), (b,a), (c,b), (b,c)}

What I Would like to have is:

{(a,b), (c,b)}

As you may notice the duplicate values have been removed completely so that two tuples never have the same elements inside regardless of order.

How can I tell the set to disregard the order of the elements in the tuple and just check the values between the tuples?

解决方案

Okay, so you've got a set {c1, c2, c3, ...}, where each cN is itself a collection of some sort.

If you don't care about the order of the elements in cN, but do care that it is unique (disregarding order), then cN should be a frozenset1 rather than a tuple:

>>> orig = {("a", "b"), ("b", "a"), ("c", "b"), ("b", "c")}
>>> uniq = {frozenset(c) for c in orig}
>>> uniq
{frozenset(['b', 'a']), frozenset(['b', 'c'])}

As a general rule, choosing an appropriate data type from those provided by Python is going to be more straightforward than defining and maintaining custom classes.


1 It can't be a set, because as a member of a larger set it needs to be hashable.

这篇关于从 python 集合中获取唯一的元组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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