为什么不能使用子集运算符< =?来比较集合和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
>>>
答案 0 :(得分:6)
使用frozenset
object代替; sets
module已被弃用,与内置类型无法比较:
>>> 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
Python set
和frozenset
确实接受了许多运算符和函数的任何序列,因此反转您的测试也有效:
>>> X
frozenset([1, 2, 3])
>>> set([1,2,3,4]) >= X
True
这同样适用于.issubset()
和sets.ImmutableSet
类的sets.Set
功能:
>>> X.issubset(set([1,2,3,4]))
True
但不要混用已弃用的类型和新的内置函数完全是最佳选择。