TRX*_*TRX 2 python set python-2.7
为什么不能使用子集运算符<=来比较集合和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
>>>
Run Code Online (Sandbox Code Playgroud)
改为使用frozenset对象 ; 该sets模块已被弃用,与内置类型无法比较:
>>> X = frozenset([1,2,3])
>>> X <= set([1,2,3,4])
True
Run Code Online (Sandbox Code Playgroud)
从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
Run Code Online (Sandbox Code Playgroud)
Python set并且frozenset接受许多运算符和函数的任何序列,因此反转测试也有效:
>>> X
frozenset([1, 2, 3])
>>> set([1,2,3,4]) >= X
True
Run Code Online (Sandbox Code Playgroud)
这同样适用于和类的.issubset()函数:sets.ImmutableSetsets.Set
>>> X.issubset(set([1,2,3,4]))
True
Run Code Online (Sandbox Code Playgroud)
但不混合已弃用的类型和新的内置插件完全是最佳选择.
| 归档时间: |
|
| 查看次数: |
737 次 |
| 最近记录: |