繁体   English   中英

如何修复 python 数组中 for 循环的值错误?

[英]How can I fix value error on for-loop in python array?

对于家庭作业,我们被要求生成下面的特定数组,并使用 for 循环查找数组中偶数的计数。 运行我的 for 循环后,我遇到了值错误。

Q2 = np.random.randint(0, 1000, size = (10, 10))
print("The list of numbers in Q2 array = ", Q2)

even_count = 0
odd_count = 0            

for i in range(len(Q2)):
    if(Q2[i] % 2 == 0):
        even_count = even_count + 1
    else:
        odd_count = odd_count + 1

print("The count of the even numbers in Q2 array = ", even_count)

当我运行 for 循环时收到以下消息: ValueError:具有多个元素的数组的真值不明确。 使用 a.any() 或 a.all()

我已经搜索了这个问题的答案,并找到了值错误和布尔值的各种解释,但没有一个对我的代码类型有帮助。 或者没有详细说明 Python 的新手理解(我!)任何帮助将不胜感激!

Q2 是数组的数组,因此您需要另一个for循环。

import numpy as np


Q2 = np.random.randint(0, 1000, size = (10, 10))
print("The list of numbers in Q2 array = ", Q2)

even_count = 0
odd_count = 0            

for i in Q2:
    for j in i:
      if (j % 2 == 0):
        even_count = even_count + 1
      else:
        odd_count = odd_count + 1

print("The count of the even numbers in Q2 array = ", even_count)

您正在生成一个二维数组 (10 x 10)。 所以Q2[i]仍然是一个(一维)数组,而不是您所期望的单个 integer。 因此会出现错误,因为在您的子数组中您可能同时拥有偶数和奇数 - 换句话说,正如错误消息所述,您检查的真值不明确。

男二次循环,或者干脆创建一个一维数组

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM