[英]Set difference versus set subtraction
What distinguishes -
and .difference()
on sets?集合上的
-
和.difference()
有何区别? Obviously the syntax is not the same, one is a binary operator, the other is an instance method.显然语法不一样,一个是二元运算符,一个是实例方法。 What else?
还有什么?
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...
can take any iterable as the second arg while both need to be sets to use -
, there is no difference in the output. set.difference, set.union...
可以将任何可迭代对象作为第二个参数,而两者都需要设置为使用-
,输出没有区别。
Operation Equivalent Result
s.difference(t) s - t new set with elements in s but not in t
With .difference you can do things like:使用 .difference 您可以执行以下操作:
s1 = set([1,2,3])
print(s1.difference(*[[3],[4],[5]]))
{1, 2}
It is also more efficient when creating sets using the *(iterable,iterable)
syntax as you don't create intermediary sets, you can see some comparisons here使用
*(iterable,iterable)
语法创建集合时也更有效*(iterable,iterable)
因为您不创建中间集合,您可以在此处查看一些比较
On a quick glance it may not be quite evident from the documentation but buried deep inside a paragraph is dedicated to differentiate the method call with the operator version快速浏览一下, 文档中可能不太明显,但埋藏在一个段落深处,专门用于区分方法调用与操作符版本
Note, the non-operator versions of union(), intersection(), difference(), and symmetric_difference(), issubset(), and issuperset() methods will accept any iterable as an argument.
请注意,union()、intersection()、difference() 和 symmetric_difference()、issubset() 和 issuperset() 方法的非运算符版本将接受任何可迭代对象作为参数。 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 readableset('abc').intersection('cbs')
.这排除了像
set('abc') & 'cbs'
这样容易出错的结构,取而代之的是更具可读性的set('abc').intersection('cbs')
。
The documentation appears to suggest that difference can take multiple sets, so it is possible that it might be more efficient and clearer for things like:该文档似乎表明差异可能需要多组,因此对于以下内容可能更有效和更清晰:
s1 = set([1, 2, 3, 4])
s2 = set([2, 5])
s3 = set([3, 6])
s1.difference(s2, s3) # instead of s1 - s2 - s3
but I would suggest some testing to verify.但我建议进行一些测试来验证。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.