如何在 Python 中创建一组集合?

发布于 2024-11-05 16:04:18 字数 476 浏览 1 评论 0原文

我正在尝试用 Python 制作一组集合。我不知道该怎么做。

从空集 xx 开始:

xx = set([])
# Now we have some other set, for example
elements = set([2,3,4])
xx.add(elements)

但我得到

TypeError: unhashable type: 'list'

或者

TypeError: unhashable type: 'set'

Is it possible to have a set of set in Python?

我正在处理大量的集合,并且我希望能够不必处理重复的集合(集合 A1、A2、...、An 的集合 B,如果 Ai = Aj,则 An 将“取消”两个集合)

I'm trying to make a set of sets in Python. I can't figure out how to do it.

Starting with the empty set xx:

xx = set([])
# Now we have some other set, for example
elements = set([2,3,4])
xx.add(elements)

but I get

TypeError: unhashable type: 'list'

or

TypeError: unhashable type: 'set'

Is it possible to have a set of sets in Python?

I am dealing with a large collection of sets and I want to be able to not have to deal duplicate sets (a set B of sets A1, A2, ...., An would "cancel" two sets if Ai = Aj)

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

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

发布评论

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

评论(4

冬天旳寂寞 2024-11-12 16:04:18

Python 抱怨是因为内部 set 对象是可变的,因此不可散列。解决方案是使用 frozenset内部集,以表明您无意修改它们。

xx = set([])
# Nested sets must be frozen
elements = frozenset([2,3,4])
xx.add(elements)

Python's complaining because the inner set objects are mutable and thus not hashable. The solution is to use frozenset for the inner sets, to indicate that you have no intention of modifying them.

xx = set([])
# Nested sets must be frozen
elements = frozenset([2,3,4])
xx.add(elements)
蛮可爱 2024-11-12 16:04:18

人们已经提到你可以使用 frozenset() 来做到这一点,所以我只添加一个代码如何实现这一点:

例如,您想要从以下列表中创建一组集合:

t = [[], [1, 2], [5], [1, 2, 5], [1, 2, 3, 4], [1, 2, 3, 6]]

您可以通过以下方式创建集合:

t1 = set(frozenset(i) for i in t)

People already mentioned that you can do this with a frozenset(), so I will just add a code how to achieve this:

For example you want to create a set of sets from the following list of lists:

t = [[], [1, 2], [5], [1, 2, 5], [1, 2, 3, 4], [1, 2, 3, 6]]

you can create your set in the following way:

t1 = set(frozenset(i) for i in t)
青春如此纠结 2024-11-12 16:04:18

在内部使用 frozenset

Use frozenset inside.

少女情怀诗 2024-11-12 16:04:18

所以我遇到了完全相同的问题。我想创建一个作为一组集合工作的数据结构。问题是集合必须包含不可变对象。因此,您可以做的就是将其作为一组元组。这对我来说效果很好!

A = set()
A.add( (2,3,4) )##adds the element
A.add( (2,3,4) )##does not add the same element
A.add( (2,3,5) )##adds the element, because it is different!

So I had the exact same problem. I wanted to make a data structure that works as a set of sets. The problem is that the sets must contain immutable objects. So, what you can do is simply make it as a set of tuples. That worked fine for me!

A = set()
A.add( (2,3,4) )##adds the element
A.add( (2,3,4) )##does not add the same element
A.add( (2,3,5) )##adds the element, because it is different!
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文