2

为什么不能使用子集运算符 <= 比较集合和 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
>>> 
4

1 回答 1

7

改为使用frozenset对象;该sets模块已被弃用,无法与内置类型进行比较:

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

sets模块的文档中:

2.6 版后已弃用:内置set/frozenset类型替换了此模块。

如果您对使用该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

Pythonset并且frozenset确实接受许多运算符和函数的任何序列,因此反转您的测试也可以:

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

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

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

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

于 2013-08-29T13:10:29.570 回答