简体   繁体   English

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

[英]How can I create a Set of Sets in Python?

I'm trying to make a set of sets in Python. I can't figure out how to do it.我正在尝试在Python中制作一套。我不知道该怎么做。

Starting with the empty set xx :从空集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?可不可以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)我正在处理大量的集合,我希望能够不必处理重复的集合(集合 B 的集合 A1,A2,....,如果 Ai = Aj,An 将“取消”两个集合)

Python's complaining because the inner set objects are mutable and thus not hashable. Python 的抱怨是因为内部set对象是可变的,因此不可散列。 The solution is to use frozenset for the inner sets, to indicate that you have no intention of modifying them.解决方案是对内部集合使用frozenset ,以表明您无意修改它们。

People already mentioned that you can do this with a frozenset() , so I will just add a code how to achieve this:人们已经提到你可以使用freezeset()来做到这一点,所以我将添加一个代码来实现这一点:

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)

在里面使用frozenset

截至 2020 年,官方 Python 文档建议使用frozenset来表示集合。

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!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM