【问题标题】:automatically make m variables for each row of (m x n) 2d ndarray自动为 (m x n) 2d ndarray 的每一行生成 m 个变量
【发布时间】:2020-06-23 22:42:48
【问题描述】:

假设我有一个 m x n 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)

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

谢谢!

【问题讨论】:

    标签: python matrix vectorization


    【解决方案1】:

    一个选项是传入整个矩阵,然后传入内部,如果你想对所有行应用相同的方程,那么你可以按如下方式遍历行

    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]))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-11-18
      • 1970-01-01
      • 1970-01-01
      • 2013-03-20
      • 1970-01-01
      • 2014-12-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多