ValueError:如何遍历布尔True / False语句的元组?

时间:2015-12-11 16:33:47

标签: python numpy boolean iteration tuples

我有一个numpy ndarray tup1语句TrueFalse

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

3 个答案:

答案 0 :(得分:2)

你有一个二维数组,所以只需要一个嵌套的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()

答案 1 :(得分:0)

您无法将列表与布尔值进行比较。您可以使用np.array.all()属性检查所有项目是否为True,如果数组中有任何True,则使用any(),以便您可以使用not any检查所有项目这些项目都是假的:

>>> import numpy as np
>>> 
>>> tup1 = np.array([[ True, False, False, False],
...        [ True, False, False, False],
...        [False, False, False, False],
...        [ True,  True, False, False]], dtype=bool)
>>> for i in tup1:
...     if not i.any():
...        print i
... 
[False False False False]

答案 2 :(得分:0)

你只需要在每个子阵列上调用.all,如果所有值都为False if not ele.all()将评估为True,如果有任何True值,那么它将评估为False。

import  numpy as np

arr = np.array([[ True, False, False, False],
       [ True, False, False, False],
       [False, False, False, False],
       [ True,  True, False, False]], dtype=bool)

for ele in arr:
    if not ele.all(): 
      # all values are False

如果你想要每个布尔值,你可以在数组上调用.flat

for ele in arr.flat:
    if not ele:
      .....

使用更大的数组进行某些计时,使用.flat比使用两个for循环要快得多:

In [5]: %%timeit
for row in arr:
    for item in row:
      pass
   ...: 
100 loops, best of 3: 4.13 ms per loop

In [6]: %%timeit
for ele in arr.flat:
    pass
   ...: 
1000 loops, best of 3: 231 µs per loop