将空集添加到python中的Frozenset中的一组集合中 [英] Add the empty set to a family of sets in a frozenset in python

查看:165
本文介绍了将空集添加到python中的Frozenset中的一组集合中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我生成了一个冻结集

Suppose I generate a frozenset with

A = frozenset(frozenset([element]) for element in [1,2,3])

我有空套

E = frozenset(frozenset())

现在我想同时使用这两个集合:

Now I want to have the union of both sets:

U = A | E

这给了我

frozenset({frozenset({2}), frozenset({3}), frozenset({1})})

这假定包含空冻结集的冻结集本身就是空的.但是,我想拥有

this assumes, that a frozenset, containing an empty frozenset is itself empty. However, I'd like to have

frozenset({frozenset({}), frozenset({2}), frozenset({3}), frozenset({1})})

因此,我想将空集显式添加到集合中.例如,在我认为构建电源集时这是必需的吗?

So, I'd like to add the empty set explicitly to the set. This is, for example, necessary in my opinion when constructing a power set?

所以:一个仅包含空集本身的空集集是空的吗?在Python中,是否有一种方法可以使用变量类型setfrozenset将空集显式包含到一组集合中?

So: Is a family of sets that only contains the empty set itself empty? Is there a way, in Python, to explicitly include an empty set into a family of sets using the variable types set and frozenset?

推荐答案

E是一个空集,没有任何元素:

E is an empty set, with no elements:

>>> frozenset(frozenset())
frozenset()

这是因为fronenset()的参数是一个可重复添加值的. frozenset()是一个空的迭代器,因此不添加任何内容.

That's because the argument to fronenset() is an iterable of values to add. frozenset() is an empty iterable, so nothing is added.

如果您希望E是一个包含一个元素的集合,则需要传入一个包含一个元素的可迭代对象.使用{...}设置符号,或单个元素元组(...,),或列表[...]:

If you expected E to be a set with one element, you need to pass in an iterable with one element; use {...} set notation, or a single element tuple (...,), or a list [...]:

>>> frozenset({frozenset()})  # pass in a set() with one element.
frozenset({frozenset()})

现在您将获得预期的输出:

Now you get your expected output:

>>> A = frozenset(frozenset([element]) for element in [1,2,3])
>>> E = frozenset({frozenset()})
>>> A | E
frozenset({frozenset({3}), frozenset({2}), frozenset({1}), frozenset()})

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

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