首页 > 解决方案 > 为 (mxn) 2d ndarray 的每一行自动生成 m 个变量

问题描述

假设我有 amxn numpy 矩阵,我需要为矩阵的每一行创建 m 个变量。有没有一种自动的方法来生成这些变量,然后在我的脚本中一次调用它们?

例如,而不是说

matrix = np.random.randn(5, 3)
a = matrix[0,:]
b = matrix[1,:]
c = matrix[2,:]
d = matrix[3,:]
e = matrix[4,:]

res = someOperation(a, b, c, d, e)

有没有办法为一些任意大小的矩阵自动生成这些变量,然后同时调用它们?我有一个包含大量行的矩阵,当然必须有一种更优雅的方式。

谢谢!

标签: pythonmatrixvectorization

解决方案


一个选项是传入整个矩阵,然后传入内部,如果要将相同的方程应用于所有行,则可以按如下方式遍历行

def someOperation(matrix):
    for row in matrix:
        print(row)

matrix = np.random.randn(5, 3)
res = someOperation(matrix)

否则,如果您希望所有变量都作为字母,您可以做的最接近的是使用字典,如下所示,这只允许字母表中的字母数量,但如果您愿意,您可以随时重复字母。

import string

matrix = np.random.randn(5, 3)
alphabets = string.ascii_lowercase
matrixDictionary = {}

for i, row in enumerate(matrix):
    matrixDictionary[alphabets[i]] = row

# example of how to access the key and row
for key in matrixDictionary.keys():
    print(str(key) + " | " + str(matrixDictionary[key]))

推荐阅读