[英]Python: How to pass functions to another function as arguments?
I have 2 custom functions: 我有2个自定义函数:
f(), g()
I want to pass all months to them, and pass them another function as follows: 我想将所有月份传递给他们,并传递给他们另一个函数,如下所示:
x(f("Jan"), g("Jan"), f("Feb"), g("Feb"), f("Mar"), g("Mar"), ...)
How is it done in short way? 怎么做到的呢?
Best Regards 最好的祝福
So, first of all, we want to call f()
and g()
on each item of a list. 因此,首先,我们要在列表的每个项目上调用
f()
和g()
。 We can do this with a list comprehension : 我们可以通过列表理解来做到这一点:
[(f(month), g(month)) for month in months]
This produces a list of tuples, but we want a flat list, so we use itertools.chain.from_iterable()
to flatten it (or in this case, just a generator expression): 这会生成一个元组列表,但是我们需要一个平面列表,因此我们使用
itertools.chain.from_iterable()
来对其进行展平(或者在这种情况下,只是一个生成器表达式):
from itertools import chain
chain.from_iterable((f(month), g(month)) for month in months)
Then we unpack this iterable into the arguments for x()
: 然后,我们将此可迭代程序解压缩到
x()
的参数中:
x(*chain.from_iterable((f(month), g(month)) for month in months))
Edit: If you wish to pass the functions ready to be executed with that parameter, without executing them, it's functools.partial()
to the rescue: 编辑:如果您希望传递准备使用该参数执行的函数,而不执行它们,则将
functools.partial()
传递给救援人员:
from functools import partial
[(partial(f, month), partial(g, month)) for month in months]
This would mean the parameters to x()
would be functions that, when called, run f()
or g()
as appropriate, with the month filled as given to the partial. 这意味着
x()
的参数将是一些函数,这些函数在调用时将根据需要运行f()
或g()
,并按照指定的月份填充月份。 This can, of course, be expanded out in the same way as before. 当然,可以像以前一样扩展它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.