我有一个 numpy ndarray tup1
语句 True
和 False
print(tup1)
array([[ True, False, False, False],
[ True, False, False, False],
[False, False, False, False],
[ True, True, False, False]], dtype=bool)
我想通过以下方式迭代这个元组tup1
:
for i in tup1:
if i == True:
pass
else:
do something
这将对所有“False”条目执行一些操作。但是,这不起作用:我收到以下错误:
---------------------------------------------------------------------------
ValueError
Traceback (most recent call last)
<ipython-input-57-0d2a4ade1205> in <module>()
1 for i in tup1:
----> 2 if i == True:
3 pass
4 else:
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
最佳答案
你有一个二维数组,所以只需创建一个嵌套的 for 循环,首先迭代每一行,然后迭代值:
for row in tup1:
for item in row:
if item: #equivalent to `if item == True`
pass
else:
dosomething()
或简化为:
for row in tup1:
for item in row:
if not item: #equivalent to `if item == False`
dosomething()
关于python - 值错误: How to iterate through a tuple of Boolean True/False statements?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34228259/