Python 集合运算的运算符和非运算符版本之间的差异
使用 intersection()
方法或 python 集合上的 &
运算符。我读到,在以前的版本中, &
的参数必须是一个集合,而不仅仅是任何可迭代的,尽管现在似乎不再是这样了。
在语义、约束、性能或简单的 Python 风格方面有区别吗?
What is the difference between using the intersection()
method or the &
operator on python sets. I read about how in previous versions the arguments to &
had to be a set and not just any iterable although that seems to be no longer the case.
Is there a difference in terms of semantics, constraints, performance or simply pythonic style?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
方法可以绑定到名称以供以后使用,而运算符可以替换为operator 模块中的操作以实现更大的抽象。
The methods can be bound to names for later use, whereas the operators can be replaced by the operations in the
operator
module for the purpose of larger abstraction.功能上没有区别,尽管使用运算符速度稍快一些,因为 Python 会在特殊情况下访问这些方法。大多数程序中的性能差异并没有大到需要使用运算符的程度。
There is no difference in functionality, although using the operators is a little faster because Python special-cases access to these methods. The performance difference in most programs is not so great as to demand that the operators be used.
intersection()
将接受任何可迭代对象,而运算符仅接受集合类型。该信息位于 docs 中的方法描述下方:
The methods like
intersection()
will accept any iterable, wheras the operators will only accept set types.The info is below the method description in the docs:
以下是在 3.7 GHz CPU 上完成的 Python 3 的一些计时...
intersection
是我认为性能差异可以忽略不计的唯一一个,但其他操作在“非操作符”处似乎更快版本使用灵活性来允许任何可迭代的作为参数(而不仅仅是显式的集合)。如果决定是任意的,则显式创建
set
可能(明显或不明显)对性能产生影响,以选择将现有的非 setiterable
转换为set
只是为了使用操作员版本。设置
union
|
Difference
-
junction
&
symmetry_difference
^
我应该补充一点,上面显示的性能影响是由于显式创建集合。如果参数已经是一个集合,@kindall 有正确的答案(运算符版本可能更快)。
Here are some timings in Python 3 done on 3.7 GHz CPU...
intersection
is the only one that I would say has negligible difference in performance, but the other operations seem faster where the "non-operator" version is using the flexibility to allow anyiterable
as an argument (not just an explicitset
).It seems that explicitly creating a
set
may (obviously or not) be a performance impact, if the decision is otherwise arbitrary, to choose between converting an existing non-setiterable
into aset
just to use the operator version.Setup
union
|
difference
-
intersection
&
symmetric_difference
^
I should add that the performance impact shown above is due to explicitly creating the set. If the argument is already a set, @kindall has the right answer (operator version may be faster).