>>> from env_helper import info; info()
页面更新时间: 2024-01-19 21:55:33
运行环境:
    Linux发行版本: Debian GNU/Linux 12 (bookworm)
    操作系统内核: Linux-6.1.0-17-amd64-x86_64-with-glibc2.36
    Python版本: 3.11.2

2.3. 充分利用Lazy evaluation的特性

Lazy evaluation常被译为“延迟计算”或“惰性计算”,指的是仅仅在真正需要执行的时 候才计算表达式的值。 充分利用Lazy evaluation的特性带来的好处主要体现在以下两个方面:

2.3.1. 避免不必要的计算,带来性能上的提升

对于Python中的条件表达式 if X and y ,在 xFalse 的情况下 y 表达式的值将不再计算。 而对于 if x or y ,当 x 的值为 True 的时候将直接返回,不再计算 y 的值,因此编程中应该充分利用该特性。

下面的例子用于判断一个单词 是不是指定的缩写形式。

>>> from time import time
>>> t = time ()
>>> abbreviations = ['cf.',' e.g.','ex.','etc.','fig.','i.e.','Mr.','vs.']
>>> for i in range (1000000):
>>>     for w in (' Mr.','Hat1','is','chasing', 'the','black', ' cat',  '.'):
>>>         if w in abbreviations:
>>>             #if w[-1] __ '.' and w in abbreviations:
>>>             pass
>>> print ('total run time:')
>>> print (time()-t)
total run time:
1.1350810527801514
>>> from time import time
>>> t = time ()
>>> abbreviations = ['cf.',' e.g.','ex.','etc.','fig.','i.e.','Mr.','vs.']
>>> for i in range (1000000):
>>>     for w in (' Mr.','Hat1','is','chasing', 'the','black', ' cat',  '.'):
>>>         # if w in abbreviations:
>>>         if w[-1] == '.' and w in abbreviations:
>>>             pass
>>> print ('total run time:')
>>> print (time()-t)
total run time:
0.8401193618774414

如果使用注释行代替第一个if,运行的时间大约会节省10%。因此在编程过程中,如果对于or条件表达式应该将值为真可能性较高的变量写在or的前面,而and则应该推后。

2.3.2. 节省空间,使得无限循环的数据结构成为可能

Python中最典型的使用延迟计算的例子就是生成器表达式了,它仅在每次需要计算的时候才通过yield产生所需要的元素。 斐波那契数列在Python中实现起来就显得相当简单,而while True也不会导致其他语言中所遇到的无限循环的问题。

>>> def fib ():
>>>     a,b=0,1
>>>     while True:
>>>         yield a
>>>         a, b =b, a+b
>>> from itertools import islice
>>> print (list (islice (fib () , 5)))
[0, 1, 1, 2, 3]

Lazy evaluation并不是一个很大、很新鲜的话题,但古人云“不积跬步无以至千里”, 小小的改进便能写出更为优化的代码,何乐而不为呢?