在Python中调用函数集的有效方法
我有一组函数:
functions=set(...)
所有函数都需要一个参数 x。
python中执行类似操作的最有效方法是什么:
for function in functions:
function(x)
I have a set of functions:
functions=set(...)
All the functions need one parameter x.
What is the most efficient way in python of doing something similar to:
for function in functions:
function(x)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您给出的代码
...似乎没有对调用
function(x)
的结果执行任何操作。如果确实如此,这意味着这些函数被调用是因为它们的副作用,那么就没有更多的 Python 替代方案了。 只需保留您的代码即可。† 这里要明确的一点是sp;
避免在列表推导中使用具有副作用的函数。
至于效率:我希望使用其他任何东西而不是简单的循环不会提高运行时间。如有疑问,请使用
timeit
。例如,以下测试似乎表明常规 for 循环比列表理解更快。 (我想,我不愿意从这个测试中得出任何一般性结论):但是,即使这些测试表明列表理解更快,但重点仍然是你不应该使用它们当涉及副作用时,为了可读性。
†:嗯,我会在函数中编写
for f
,因此function
和functions
之间的区别是更明显。但这不是这个问题的目的。The code you give,
...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, isAvoid functions with side-effects in list-comprehensions.
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):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.
†: Well, I'd write
for f in functions
, so that the difference beteenfunction
andfunctions
is more pronounced. But that's not what this question is about.如果您需要输出,列表理解就可以了。
If you need the output, a list comprehension would work.
我有点怀疑这会对程序的总运行时间产生多大影响,但我想你可以这样做:
缺点是你将创建一个新列表,然后立即扔掉,但是它应该比 for 循环稍微快一些。
无论如何,请确保对代码进行分析,以确认这确实是您需要解决的瓶颈。
I'm somewhat doubtful of how much of an impact this will have on the total running time of your program, but I guess you could do something like this:
The downside is that you will create a new list that you immediatly toss away, but it should be slightly faster than just the for-loop.
In any case, make sure you profile your code to confirm that this really is a bottleneck that you need to take care of.
编辑:我使用 timeit 重新进行了测试
我的新测试代码:
这是此计时的结果。
我原来的基于 time.time() 的计时几乎与此测试一致,简单的 for 循环似乎是最有效的。
Edit: I redid the test using timeit
My new test code:
Here is the results from this timing.
My original, time.time() based timings are pretty much inline with this testing, plain for loops seem to be the most efficient.