python - 为什么我不能比较 python 2.7 中的集合和不可变集合

标签 python python-2.7 set

为什么不能使用子集运算符 <= 比较集合和 ImmutableSet?例如。运行以下代码。这里有什么问题?任何帮助表示赞赏。我正在使用 Python 2.7。

>>> from sets import ImmutableSet
>>> X = ImmutableSet([1,2,3])
>>> X <= set([1,2,3,4])
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/sets.py", line 291, in issubset
    self._binary_sanity_check(other)
  File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/sets.py", line 328, in _binary_sanity_check
    raise TypeError, "Binary operation only permitted between sets"
TypeError: Binary operation only permitted between sets
>>> 

最佳答案

使用 frozenset object反而; sets module已被弃用,无法与内置类型相媲美:

>>> X = frozenset([1,2,3])
>>> X <= set([1,2,3,4])
True

来自 sets 模块的文档:

Deprecated since version 2.6: The built-in set/frozenset types replace this module.

如果您对使用 sets 模块的代码感到困惑,请在比较时只使用它的类型:

>>> from sets import Set, ImmutableSet
>>> Set([1, 2, 3]) <= set([1, 2, 3, 4])
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/Users/mj/Development/Libraries/buildout.python/parts/opt/lib/python2.7/sets.py", line 291, in issubset
    self._binary_sanity_check(other)
  File "/Users/mj/Development/Libraries/buildout.python/parts/opt/lib/python2.7/sets.py", line 328, in _binary_sanity_check
    raise TypeError, "Binary operation only permitted between sets"
TypeError: Binary operation only permitted between sets
>>> ImmutableSet([1, 2, 3]) <= Set([1, 2, 3, 4])
True

Python setfrozenset 确实接受许多运算符和函数的任何序列,因此反转您的测试也有效:

>>> X
frozenset([1, 2, 3])
>>> set([1,2,3,4]) >= X
True

这同样适用于 sets.ImmutableSetsets.Set 类上的 .issubset() 函数:

>>> X.issubset(set([1,2,3,4]))
True

但不混合已弃用的类型和新的内置类型完全是最佳选择。

关于python - 为什么我不能比较 python 2.7 中的集合和不可变集合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18511962/

相关文章:

python - 如何在 Python 中将我创建的索引写入文件

windows - 权限被拒绝 : Untitled. ipynb Windows 10 AWS 工作区

python - 从 div 标签 Python 中提取数据

java - 为什么 TreeSet 抛出 ClassCastException?

algorithm - 如何在多个条件下选择项目

python - pandas df.apply 返回一系列相同列表(如 map ),其中应返回一个列表

python - Docker容器网络偶尔失败

python - 将一个值引用到列表时,是否可以在 python 中快速检查一个值是否等于另一个值?

python lambda无法检测打包的模块

arrays - 如何在 Core Data 中存储一组自定义(和重复)对象?