列表理解中的函数-是否多次评估 [英] function inside list comprehension - is it evaluated multiple times
本文介绍了列表理解中的函数-是否多次评估的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
哪个是在python中进行列表理解的更好方法(就计算时间和cpu周期而言). 在示例(1)中,值f(r)是在每次迭代中求值还是仅求值一次并缓存?
Which one's a better way of doing list comprehension in python (in terms of computation time & cpu cycles). In example (1) is the value f(r) evaluated in each iteration or is it evaluated once and cached ?
-
y = [x*f(r) for x in xlist]
c = f(r)
y = [x*c for x in xlist]
其中
def f(r):
... some arbitrary function ...
推荐答案
我可能会选择后者,因为Python编译器不知道该函数是否具有副作用,因此会为每个元素调用该函数.
I would probably choose the latter because the Python compiler doesn't know if the function has side-effects so it is called for each element.
这篇关于列表理解中的函数-是否多次评估的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文