Runtime difference between set.discard and set.remove methods in Python?(Python中set.discard和set.remove方法之间的运行时差异?)
问题描述
这些方法的官方 Python 2.7 文档听起来几乎相同,与唯一的区别似乎是 remove() 会引发 KeyError 而 discard 不会.
我想知道这两种方法的执行速度是否存在差异.如果做不到这一点,它们之间是否有任何有意义的区别(除了 KeyError)?
在一种情况下引发异常是一个非常有意义的区别.如果尝试从不存在的集合中删除元素会出错,则最好使用 set.remove() 而不是 p>set.discard().
这两种方法在实现上是相同的,除了相比 set_discard() set_remove()函数添加行:
if (rv == DISCARD_NOTFOUND) {set_key_error(key);返回空值;}这会引发 KeyError.由于这需要更多的工作,set.remove() 比 teeniest 慢一点;您的 CPU 在返回之前必须进行一项额外的测试.但是,如果您的算法依赖于异常,那么额外的分支测试就无关紧要了.
The official Python 2.7 docs for these methods sounds nearly identical, with the sole difference seeming to be that remove() raises a KeyError while discard does not.
I'm wondering if there is a difference in execution speed between these two methods. Failing that, is there any meaningful difference (barring KeyError) between them?
Raising an exception in one case is a pretty meaningful difference. If trying to remove an element from a set that is not there would be an error, you better use set.remove() rather than set.discard().
The two methods are identical in implementation, except that compared to set_discard() the set_remove() function adds the lines:
if (rv == DISCARD_NOTFOUND) {
set_key_error(key);
return NULL;
}
This raises the KeyError. As this is slightly more work, set.remove() is a teeniest fraction slower; your CPU has to do one extra test before returning. But if your algorithm depends on the exception then the extra branching test is hardly going to matter.
这篇关于Python中set.discard和set.remove方法之间的运行时差异?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Python中set.discard和set.remove方法之间的运行时差异?
基础教程推荐
- 对多索引数据帧的列进行排序 2022-01-01
- Python,确定字符串是否应转换为 Int 或 Float 2022-01-01
- 究竟什么是“容器"?在蟒蛇?(以及所有的 python 容器类型是什么?) 2022-01-01
- kivy 应用程序中的一个简单网页作为小部件 2022-01-01
- Python 中是否有任何支持将长字符串转储为块文字或折叠块的 yaml 库? 2022-01-01
- Kivy 使用 opencv.调整图像大小 2022-01-01
- 比较两个文本文件以找出差异并将它们输出到新的文本文件 2022-01-01
- 在 Python 中将货币解析为数字 2022-01-01
- matplotlib 设置 yaxis 标签大小 2022-01-01
- 在 Django Admin 中使用内联 OneToOneField 2022-01-01
