加速Python列表和字典,让你代码更加高效
2020-11-13 本文已影响0人
Python小辰
介绍
今天,我们将讨论Python中的优化技术。在本文中,您将了解如何通过避免在列表和字典中进行重新计算来加快代码的速度。
我们先编写一个装饰器函数来计算函数的执行时间,方便测验不同代码的速度:

避免在列表中重新评估
在循环内
代码:

在上面的函数中.append每次通过循环重新计算的函数引用。执行后,上述函数所花费的总时间:

在循环外
代码:

在上面的函数中,我们对nums.append在循环外部估值,并在循环内部使用append为变量。总时间:

如您所见,当我们在for循环外部追加为一个本地变量,这将花费更少的时间,可以将代码加速201 ms。
避免在字典中重新求值
在循环内部
代码:

上述函数所花费的总时间:

Python作为一门不断发展与普及的语言,还在不断更新中。在学习时,建议找一些学习伙伴一起来学习和讨论,效果更佳。如果想学习Python,欢迎加入Python学习交流群(627012464),一起督促,一起学习。里面有开发工具,很多干货和技术资料分享!
在循环外
代码:

上述函数所花费的总时间:

如你所见,我们这里的代码速度提高了211毫秒。