2017-08-25 23 views
2

为什么set操作在使用set方法时可以使用任意可迭代操作,但不能使用操作符?为了说明我的意思:为什么只有在使用方法时,集合操作才能用于迭代?

>>> {0, 1, 2, 3}.intersection([0, 1]) 
{0, 1} 
>>> {0, 1, 2, 3} & [0, 1] 
Traceback (most recent call last): 
    File "<stdin>", line 1, in <module> 
TypeError: unsupported operand type(s) for &: 'set' and 'list' 
>>> 
>>> {0, 1, 2, 3}.union([4, 5]) 
{0, 1, 2, 3, 4, 5} 
>>> {0, 1, 2, 3} | [4, 5] 
Traceback (most recent call last): 
    File "<stdin>", line 1, in <module> 
TypeError: unsupported operand type(s) for |: 'set' and 'list' 
+3

你在问为什么Python开发人员设计'set'这种方式,或者你只是想要一个链接到文档中出现这种行为? (它在这里:https://docs.python.org/3/library/stdtypes.html#frozenset.copy) – jwodder

+0

它看起来像我从来没有达到文档的那一部分。 – planetp

回答

7

docs

注,union()非运营商的版本,intersection()difference()symmetric_difference()issubset()issuperset()方法将接受任何可迭代的一个论点。相反,他们的基于操作员的对应方要求他们的参数是集合。 这排除了易于出错的结构,如set('abc') & 'cbs'有利于更易于读取的set('abc').intersection('cbs')

这样被认为不太容易出错。

相关问题