【问题标题】:Looping through a numpy matrix循环遍历一个 numpy 矩阵
【发布时间】:2017-12-12 19:30:02
【问题描述】:

为什么下面的代码不起作用?

import numpy

grid = numpy.matrix([[1,0,1,1],[1,1,0,0],[1,0,1,0],[0,0,0,1]])
i = 0
for line in grid:
    for block in line:
        if block == 1:
            i += 1    
print("Grid has " + str(i) + " times number 1")

我以为它会先循环遍历每一行,然后遍历该行的每个元素并将其与 1 进行比较,但我收到此错误:

Traceback (most recent call last):
File "python", line 7, in <module>
ValueError: The truth value of an array with more than one element is 
ambiguous. Use a.any() or a.all()

【问题讨论】:

  • 如果你使用numpy.array而不是numpy.matrix,你就不会遇到这个问题。说真的,numpy.matrix 不值得。

标签: python python-3.x numpy for-loop matrix


【解决方案1】:

遍历 numpy.matrix 矩阵会生成 1 行 numpy.matrix 矩阵,每行一个。

迭代 1 行 numpy.matrix 矩阵会生成 1 行 numpy.matrix 矩阵,而不是单个单元格。

不要使用numpy.matrix。这根本不值得。另外,如果可以的话,不要循环遍历 NumPy 对象:

grid = numpy.array([[1,0,1,1],[1,1,0,0],[1,0,1,0],[0,0,0,1]])
i = grid.sum()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-16
    • 2013-10-29
    • 2022-01-22
    • 1970-01-01
    • 2022-08-05
    相关资源
    最近更新 更多