简体   繁体   English

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

[英]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.

相关问题 如何在Python中将函数或运算符作为参数传递给函数? - How can I pass functions or operators as arguments to a function in Python? Python 3:如何从另一个文件调用函数并将参数传递给该函数? - Python 3: How to call function from another file and pass arguments to that function ? 如何在 Python 中将可变数量的函数作为参数传递 - How to pass variable number of functions as arguments in Python 如何将 arguments 传递给 Python 中的线程函数 - How to pass arguments to thread functions in Python 如何将可选的python参数传递给带有可选参数的子函数 - How to pass optional python arguments to sub-functions with optional arguments 如何将argparse参数传递给另一个python程序? - How to pass argparse arguments to another python program? 调用成员函数并在python中使用map函数传递参数 - call member functions and pass arguments with map function in python 如何传递函数列表及其所有参数在python中的另一个函数中执行? - How to pass list of function and all its arguments to be executed in another function in python? Python:如何将映射函数的输出作为参数传递 - Python: How to pass output of the map function as arguments 如何将 arguments 传递给 python 中的映射器 function? - How to pass arguments to mapper function in python?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM