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

标签 python arrays numpy matrix shapes

我试图从二维矩阵中获取 (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 列

关于python - 我怎么能总是让 numpy.ndarray.shape 返回一个二值元组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31713146/

相关文章:

python - 将 numpy (n,) 向量 reshape 为 (n,1) 向量

python filecmp.dircmp 忽略通配符

python - 在 Python 中获取网络地址和网络掩码

javascript - 计算具有不同键值的对象项

python - 从数组中删除子数组

python - Mechanize 可以通过javascript支持ajax/填写表格吗?

javascript - 如何在 jQuery ajax 调用中使用数组字符串?

arrays - 了解 J 数组

python - 将 numpy 数组重新排序为新的位长度元素,无需循环

python - python numpy数组操作+=线程安全吗?