Python:如何将函数作为参数传递给另一个函数? [英] Python: How to pass functions to another function as arguments?

查看:1263
本文介绍了Python:如何将函数作为参数传递给另一个函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有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?

最好的问候

推荐答案

因此,首先,我们要在列表的每个项目上调用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.

这篇关于Python:如何将函数作为参数传递给另一个函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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