Python 集差与集减的区别

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30986751/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 09:16:18  来源:igfitidea点击:

Difference between set difference and set subtraction

python

提问by David542

Is there any difference between the following two statements?

以下两种说法有区别吗?

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

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

采纳答案by Padraic Cunningham

set.difference, set.union...can take any iterableas the second arg while both need to be sets to use -, there is no difference in the output.

set.difference, set.union...可以将任何可迭代对象作为第二个参数,而两者都需要设置为 use -,输出没有区别。

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)语法创建集合时也更有效,因为您不创建中间集合,您可以在此处查看一些比较

回答by Brad Richardson

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.

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

回答by Abhijit

On a quick glance it may not be quite evident from the documentationbut 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. 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').

请注意,union()、intersection()、difference() 和 symmetric_difference()、issubset() 和 issuperset() 方法的非运算符版本将接受任何可迭代对象作为参数。相比之下,它们的基于运算符的对应物需要设置它们的参数。这排除了容易出错的结构,例如set('abc') & 'cbs'支持更具可读性的set('abc').intersection('cbs').