python - 值错误: How to iterate through a tuple of Boolean True/False statements?

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

最佳答案

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

相关文章:

python - 在 python 中准备一个返回矩阵有什么好处?

python - 重新加载重复日志打印的记录器

python - 使用python查找图像中黑色/灰色像素的所有坐标

java - 如何使用 JPA 持久保存 Map<Key, Boolean>

python - Pandas 使用来自 groupby 的计数创建新列

python - Django:多对多 add() 期间的 IntegrityError

python - 如何在元组列表中使用 numpy.random.choice?

python - "Numpy"类型错误 : data type "string" not understood

python - TensorFlow:获取非零张量中最小元素索引的有效方法?

java - 使用 for 循环在二维数组中打印 boolean 输入