集合差与集合减法 [英] Set difference versus set subtraction
问题描述
-
和 .difference()
在集合上有什么区别?显然语法不一样,一个是二元运算符,一个是实例方法.还有什么?
What distinguishes -
and .difference()
on sets? 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...
可以将 any iterable 作为第二个 arg 而两者都需要设置为使用-
,输出没有区别.
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.
Operation Equivalent Result
s.difference(t) s - t new set with elements in s but not in t
使用 .difference,您可以执行以下操作:
With .difference you can do things like:
s1 = set([1,2,3])
print(s1.difference(*[[3],[4],[5]]))
{1, 2}
使用 *(iterable,iterable)
语法创建集合时也更高效,因为您不创建中间集合,您可以看到一些比较 这里
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
这篇关于集合差与集合减法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!