循环通过一个numpy矩阵

时间:2017-12-12 19:30:02

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

为什么以下代码无效?

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

1 个答案:

答案 0 :(得分: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()