简体   繁体   English

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

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

For a homework assignment we were asked to generate the specific array below and find the count of the even numbers in the array using a for loop.对于家庭作业,我们被要求生成下面的特定数组,并使用 for 循环查找数组中偶数的计数。 I'm running into a value error after running my for loop.运行我的 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)

I'm getting the following message when I run the for loop: ValueError: The truth value of an array with more than one element is ambiguous.当我运行 for 循环时收到以下消息: ValueError:具有多个元素的数组的真值不明确。 Use a.any() or a.all()使用 a.any() 或 a.all()

I've searched for an answer for this problem and have found all kinds of explanation of the value error and Booleans, but none of them helped specific with my type of code.我已经搜索了这个问题的答案,并找到了值错误和布尔值的各种解释,但没有一个对我的代码类型有帮助。 Or didn't elaborate enough for someone who is very new to Python to understand (me!) Any help would be much appreciated!或者没有详细说明 Python 的新手理解(我!)任何帮助将不胜感激!

Q2 is an array of array so you need another for loop. 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)

You are generating a two-dimensional array (10 x 10).您正在生成一个二维数组 (10 x 10)。 So Q2[i] is still a (one-dimensional) array, not a single integer as you seem to expect.所以Q2[i]仍然是一个(一维)数组,而不是您所期望的单个 integer。 Hence the error, because in your subarray you may have both even and odd numbers - in other words the truth value of your check is ambiguous, as the error message says.因此会出现错误,因为在您的子数组中您可能同时拥有偶数和奇数 - 换句话说,正如错误消息所述,您检查的真值不明确。

Male two loops, or simply create a one-dimension array男二次循环,或者干脆创建一个一维数组

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

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