且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Python:如何将函数作为参数传递给另一个函数?

更新时间:2021-07-07 05:08:52

因此,首先,我们要在列表的每个项目上调用f()g().我们可以通过列表理解:

So, first of all, we want to call f() and g() on each item of a list. We can do this with a list comprehension:

[(f(month), g(month)) for month in months]

这会生成一个元组列表,但是我们需要一个平面列表,因此我们使用 itertools.chain.from_iterable() 将其展平(或在这种情况下,只是生成器表达式):

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):

from itertools import chain

chain.from_iterable((f(month), g(month)) for month in months)

然后我们解压缩将此迭代器放入参数中对于x():

Then we unpack this iterable into the arguments for x():

x(*chain.from_iterable((f(month), g(month)) for month in months))

如果希望传递准备使用该参数执行的函数,而不执行它们,则为 functools.partial() :

If you wish to pass the functions ready to be executed with that parameter, without executing them, it's functools.partial() to the rescue:

from functools import partial

[(partial(f, month), partial(g, month)) for month in months]

这意味着x()的参数将是函数,这些函数在被调用时将根据需要运行f()g(),并按指定的月份填充月份.当然,可以像以前一样扩展它.

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. This can, of course, be expanded out in the same way as before.