Skip to main content
 首页 » 编程设计

python之我怎么能总是让 numpy.ndarray.shape 返回一个二值元组

2025年05月04日9jirigala

我试图从二维矩阵中获取 (nRows, nCols) 的值,但是当它是单行时(即 x = np.array([1, 2, 3, 4])),x.shape将返回 (4,) 因此我的 (nRows, nCols) = x.shape 语句返回“ValueError: need more than 1 value to unpack”

关于如何使此声明更具适应性的任何建议?它适用于许多程序中使用的函数,应该适用于单行和多行矩阵。谢谢!

请您参考如下方法:

您可以创建一个返回行和列元组的函数,如下所示:

def rowsCols(a): 
    if len(a.shape) > 1: 
        rows = a.shape[0] 
        cols = a.shape[1] 
    else: 
        rows = a.shape[0] 
        cols = 0 
    return (rows, cols) 

其中 a 是您输入到函数的数组。下面是使用该函数的示例:

import numpy as np 
 
x = np.array([1,2,3]) 
 
y = np.array([[1,2,3],[4,5,6],[7,8,9],[10,11,12]]) 
 
def rowsCols(a): 
    if len(a.shape) > 1: 
        rows = a.shape[0] 
        cols = a.shape[1] 
    else: 
        rows = a.shape[0] 
        cols = 0 
    return (rows, cols) 
 
(nRows, nCols) = rowsCols(x) 
 
print('rows {} and columns {}'.format(nRows, nCols)) 
 
(nRows, nCols) = rowsCols(y) 
 
print('rows {} and columns {}'.format(nRows, nCols)) 

这会打印第 3 行和第 0 列,然后是第 4 行和第 3 列。或者,您可以使用 atleast_2d 函数以获得更简洁的方法:

(r, c) = np.atleast_2d(x).shape 
 
print('rows {}, cols {}'.format(r, c)) 
 
(r, c) = np.atleast_2d(y).shape 
 
print('rows {}, cols {}'.format(r, c)) 

打印第 1 行,第 3 列 和 第 4 行,第 3 列。