0

我不想为每个函数编写同一行(如第一个代码块所示),而是想在循环的帮助下调用每个函数(如第二个代码块所示)

我想要做的是:

import numpy as np
A = np.arange(9).reshape(3,3)
B = np.array([3,4,6,3,2,7,0,1,7]).reshape(3,3)
#################

def calc_stats(mat):
    print(mat.max())
    print(mat.min())
    print(mat.mean())

calc_stats(A)
calc_stats(B)

但是通过使用循环,我可以在每次迭代时更改函数的名称。
与此类似的东西:

import numpy as np
A = np.arange(9).reshape(3,3)
B = np.array([3,4,6,3,2,7,0,1,7]).reshape(3,3)
#################

def calc_stats(mat):
    for names in ["mean", "max", "min"]:
        print(mat.names())

calc_stats(A)
calc_stats(B)

当然,上面的代码不起作用,因为变量不能用作函数名,但是有什么方法可以实现我想要做的吗?


这个问题在我上次发布时已关闭,因为它似乎与这个问题相似,但我发现这篇文章中提供的答案有点难以理解或与我的问题相关。

4

2 回答 2

2

您可以保留要调用的函数列表,在提供的参数上调用每个函数

def calc_stats(mat):
    for f in [np.mean, np.max, np.min]:
        print(f(mat))

输出

>>> calc_stats(A)
4.0
8
0
>>> calc_stats(B)
3.6666666666666665
7
0
于 2021-03-05T18:39:22.593 回答
1

如果您必须使用字符串作为名称,您可以使用 getattr() 获取函数:

def calc_stats(mat):
    for name in ["mean", "max", "min"]:
        print(getattr(np,name)(mat))

输出:

calc_stats(A)
4.0
8
0

calc_stats(B)
3.6666666666666665
7
0
于 2021-03-05T19:31:28.907 回答