gpt4 book ai didi

python - 从python中的函数列表中选择函数的子集

转载 作者:太空狗 更新时间:2023-10-30 02:09:59 24 4
gpt4 key购买 nike

我有一个列表:mylist = [1,2,5,4,7,8]我已经定义了一些在此列表上运行的函数。例如:

def mean(x): ...
def std(x): ...
def var(x): ...
def fxn4(x): ...
def fxn5(x): ...
def fxn6(x): ...
def fxn7(x): ...

现在我得到了一个函数名称列表,我想在 mylist 上应用它们。

例如:fxnOfInterest = ['mean', 'std', 'var', 'fxn6']

调用这些函数最符合 Python 风格的方法是什么?

最佳答案

我不认为有 pythonic™ 方法可以解决这个问题。但在我的代码中这是很常见的情况,所以我为此编写了自己的函数:

def applyfs(funcs, args):
"""
Applies several functions to single set of arguments. This function takes
a list of functions, applies each to given arguments, and returns the list
of obtained results. For example:

>>> from operator import add, sub, mul
>>> list(applyfs([add, sub, mul], (10, 2)))
[12, 8, 20]

:param funcs: List of functions.
:param args: List or tuple of arguments to apply to each function.
:return: List of results, returned by each of `funcs`.
"""
return map(lambda f: f(*args), funcs)

在您的情况下,我将按以下方式使用它:

applyfs([mean, std, var, fxn4 ...], mylist)

请注意,您实际上不必使用函数 names(例如,在 PHP4 中您必须这样做),在 Python 中,函数本身就是可调用对象并且可以存储在列表中。

编辑:

或者可能,使用列表理解而不是 map 会更符合 pythonic:

results = [f(mylist) for f in [mean, std, var, fxn4 ...]]

关于python - 从python中的函数列表中选择函数的子集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32802833/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com