0

Instead of writing the same line for each function (as shown in the first code block), I want to call each function with the help of a loop (as shown in the 2nd code block)

What I want to be able to do is:

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)

But by the use of a loop where at each iteration I can change the name of the function.
Something similar to this:

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)

Of course, the above code doesn't work because a variable cannot be used as a function name, but is there any method to implement what I want to do?


This question got closed the last time I posted it because it seemed similar to this question, but I'm finding the answers provided in this post a bit hard to understand or relate to my question.

ray_lv
  • 99
  • 5

2 Answers2

2

You can keep a list of functions to call, the call each one on the provided argument

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

Output

>>> calc_stats(A)
4.0
8
0
>>> calc_stats(B)
3.6666666666666665
7
0
Cory Kramer
  • 114,268
  • 16
  • 167
  • 218
1

If you must use strings for the names you can obtain the functions using getattr():

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

output:

calc_stats(A)
4.0
8
0

calc_stats(B)
3.6666666666666665
7
0
Alain T.
  • 40,517
  • 4
  • 31
  • 51