集差与集减法

Set difference versus set subtraction

集合上的 -.difference() 有什么区别?显然语法不一样,一个是二元运算符,一个是实例方法。还有什么?

s1 = set([1,2,3])
s2 = set([3,4,5])

>>> s1 - s2
set([1, 2])
>>> s1.difference(s2)
set([1, 2])

set.difference, set.union... 可以将 any iterable 作为第二个参数,而两者都需要设置才能使用 -,输出没有区别。

Operation         Equivalent   Result
s.difference(t)   s - t        new set with elements in s but not in t

使用 .difference,您可以执行以下操作:

s1 = set([1,2,3])

print(s1.difference(*[[3],[4],[5]]))

{1, 2}

使用 *(iterable,iterable) 语法创建集合时效率更高,因为您不创建中间集合,您可以看到一些比较

文档似乎表明 difference 可以采用多个集合,因此它可能更有效、更清晰,例如:

s1 = set([1, 2, 3, 4])
s2 = set([2, 5])
s3 = set([3, 6])
s1.difference(s2, s3) # instead of s1 - s2 - s3

但我建议进行一些测试来验证。

乍看之下,documentation可能不太明显,但深埋在一段中,专门用于区分方法调用与运算符版本

Note, the non-operator versions of union(), intersection(), difference(), and symmetric_difference(), issubset(), and issuperset() methods will accept any iterable as an argument. In contrast, their operator based counterparts require their arguments to be sets. This precludes error-prone constructions like set('abc') & 'cbs' in favor of the more readable set('abc').intersection('cbs').