在Python中调用函数集的有效方法 [英] Efficient way of calling set of functions in Python

查看:201
本文介绍了在Python中调用函数集的有效方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一组功能:

functions=set(...)

所有函数都需要一个参数x。

All the functions need one parameter x.

什么是最有效的方法在python中做类似的事情:

What is the most efficient way in python of doing something similar to:

for function in functions:
   function(x)


推荐答案

您提供的代码,

for function in functions:
    function(x)

...似乎没有对调用 function(x)的结果做任何事情。如果确实如此,意味着这些功能被称为副作用,那么就没有更多的pythonic替代品了。 只需保留您的代码。 这里带回家的重点是

...does not appear to do anything with the result of calling function(x). If that is indeed so, meaning that these functions are called for their side-effects, then there is no more pythonic alternative. Just leave your code as it is. The point to take home here, specifically, is


                       &NBSP ;      
在列表推导中避免使用带副作用的函数。

至于效率:我希望使用其他任何东西而不是你的简单的循环不会改善运行时。如有疑问,请使用 timeit 。例如,以下测试似乎表明常规for循环比列表理解更快。 (我不愿意从这个测试中得出任何一般性的结论,认为):

As for efficiency: I expect that using anything else instead of your simple loop will not improve runtime. When in doubt, use timeit. For example, the following tests seem to indicate that a regular for-loop is faster than a list-comprehension. (I would be reluctant to draw any general conclusions from this test, thought):

>>> timeit.Timer('[f(20) for f in functions]', 'functions = [lambda n: i * n for i in range(100)]').repeat()
[44.727972984313965, 44.752119779586792, 44.577917814254761]
>>> timeit.Timer('for f in functions: f(20)', 'functions = [lambda n: i * n for i in range(100)]').repeat()
[40.320928812026978, 40.491761207580566, 40.303879022598267]

但是,再次,即使这些测试表明该列表 - 为了便于阅读,理解是更快,重要的是你不应该在涉及副作用时使用它们。

But again, even if these tests would have indicated that list-comprehensions are faster, the point remains that you should not use them when side-effects are involved, for readability's sake.

  :好吧,我在函数中为f写了,所以差值为 function 函数更加明显。但这不是这个问题的关键。

  : Well, I'd write for f in functions, so that the difference beteen function and functions is more pronounced. But that's not what this question is about.

这篇关于在Python中调用函数集的有效方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆