为什么不能使用子集运算符 <= 比较集合和 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 set
和 frozenset
确实接受许多运算符和函数的任何序列,因此反转您的测试也有效:
>>> X
frozenset([1, 2, 3])
>>> set([1,2,3,4]) >= X
True
这同样适用于 sets.ImmutableSet
和 sets.Set
类上的 .issubset()
函数:
>>> X.issubset(set([1,2,3,4]))
True
但不混合已弃用的类型和新的内置类型完全是最佳选择。
关于python - 为什么我不能比较 python 2.7 中的集合和不可变集合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18511962/