【发布时间】: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