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

标签 python

我有一个列表: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/

相关文章:

python - 替换对应于另一个数组的索引数组中的值

php - 如何将可执行文件与库文件分开?

python - django模型获取字段方法

python - 改变 QProgressbar() 的颜色

python - 游戏登录认证及安全

python - 独立移动数组中的行

python - 在Python中处理二维列表边界检查的最佳方法?

python - 如何在区域上方激活功能,在限制区域外保持事件状态

python - Mysql 创建外键

python - 在 Pytorch 中重复张量的特定列