如何在 Python 中创建一组集合? [英] How can I create a Set of Sets in Python?

查看:44
本文介绍了如何在 Python 中创建一组集合?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

从空集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'

Python 中可以有一组集合吗?

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

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

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)

推荐答案

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

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.

这篇关于如何在 Python 中创建一组集合?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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