获取带有 numpy 函数的列表并插入循环

Take a list with numpy functions and insert in loop

我需要一些帮助来遍历 numpy 函数循环。首先,我开始计算我要查找的所有值并将它们存储在字典中。

  calculations[keys[0]] = [np.mean(matrix, axis=0),np.mean(matrix, axis=1),np.mean(list)]
  calculations[keys[1]] = [np.var(matrix, axis=0),np.var(matrix, axis=1),np.var(list)]
  calculations[keys[2]] = [np.std(matrix, axis=0),np.std(matrix, axis=1),np.std(list)]
  calculations[keys[3]] = [np.max(matrix, axis=0),np.max(matrix, axis=1),np.min(list)]
  calculations[keys[4]] = [np.min(matrix, axis=0),np.min(matrix, axis=1),np.max(list)]
  calculations[keys[5]] = [np.sum(matrix, axis=0),np.sum(matrix, axis=1),np.sum(list)]

然后我想有没有更好的 war 通过循环来做到这一点。我尝试了一些 f 字符串的东西,但没有成功。

list = [i for i in range(9)]

matrix = np.reshape(list,(3,3))

keys = ['mean','variance','standard deviation', 'max','min','sum']
operator = ['np.mean','np.var','np.std','np.max','np.min','np.sum']

calculations = {}

for i in range[len(keys)]:
    
    calculations[keys[i]] = [f'{operater[0]}'(matrix, axis=0),f'{operater[0]}'(matrix, axis=1),f'{operater[0]}'(list)]

有路可走吗?

提前致谢

list 是一个关键字,因此不应用作变量,此外您需要为 range 使用圆括号 (),而不是方括号 [] . 在 Python 中,函数首先是 class 成员,因此您可以传递它们并将它们保存在列表中。只需这样做:

import numpy as np

numbers = list(range(9))

matrix = np.reshape(numbers,(3,3))

keys = ['mean','variance','standard deviation', 'max','min','sum']
operator = [np.mean, np.var, np.std, np.max, np.min, np.sum]

calculations = {}
for i in range(len(keys)):
    calculations[keys[i]] = [operator[i](matrix, axis=0),operator[i](matrix, axis=1),operator[i](numbers)]