【问题标题】:How to use the dimension of a python matrix in a loop如何在循环中使用python矩阵的维度
【发布时间】:2016-08-13 13:23:50
【问题描述】:

我正在处理一个矩阵,我们称之为 X,在 python 中。

我知道如何使用 X.shape 获取矩阵的维度,但我对在 for 循环中使用矩阵的行数特别感兴趣,我不知道如何在适合的数据类型中获取此值一个循环。

例如,想象一个简单的情况:

a = np.matrix([[1,2,3],[4,5,6]])
for i in 1:(number of rows of a)
     print i

如何自动获得“a 的行数”?

【问题讨论】:

标签: python-2.7 numpy


【解决方案1】:

X.shape[0] == X 中的行数

【讨论】:

    【解决方案2】:

    numpy 上进行表面搜索将引导您到shape。它返回一个数组维度的元组

    在您的情况下,第一个维度(轴)涉及列。您可以像访问元组的元素一样访问它:

    import numpy as np
    
    a = np.matrix([[1,2,3],[4,5,6]])
    # a. shape[1]: columns
    for i in range(0,a.shape[1]):
       print 'column '+format(i)
    
    # a. shape[0]: rows   
    for i in range(0, a.shape[0]):
       print 'row '+format(i)
    

    这将打印:

    column 0
    column 1
    column 2
    row 0
    row 1
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-07-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-11-12
      • 2020-08-19
      • 1970-01-01
      相关资源
      最近更新 更多