documentation for set operations人说:
注意,union()、intersection()的非运算符版本,
通过以下实验来测试这一点:
# Python 3.10.2 (main, Jan 15 2022, 19:56:27) [GCC 11.1.0] on linux
>>> set('ab') & set('ac')
{'a'}
# works, as expected
>>> set('ab') & 'ac'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for &: 'set' and 'str'
# doesn't work, as expected
>>> set('ab') & list('ac')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for &: 'set' and 'list'
# doesn't work, as expected
>>> set('ab') & iter('ac')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for &: 'set' and 'str_iterator'
# doesn't work, as expected
>>> set('ab') & dict(zip('ac', 'ac')).keys()
{'a'}
# works??
>>> type({}.keys())
<class 'dict_keys'>
>>> isinstance({}.keys(), (set, frozenset))
False
所以,这里有一个悖论:
-
set
操作员&
处理dict_keys
个对象; - 文件中说,它应该只适用于集合;
-
dict_keys
个对象不是集合.
为什么set运算符&
与dict_keys对象一起工作?还有其他类型的可以使用吗?如何找到这些类型的列表?