简体   繁体   English

如何检查 numpy 中数组的值?

[英]How do I check the values of an array in numpy?

the part of my code that has a problem is:我的代码有问题的部分是:

history = np.array([[0, 0, 1, 1],[1, 0, 0, 1]])
opponentsActions = history[1]
if opponentsActions == [0, 0, 0, 0]:
    print("nice")

and the error I get is: ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()我得到的错误是: ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all() ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

When you execute your check, you receive array representing comparision当您执行检查时,您会收到表示比较的数组

>>> opponentsActions == [0, 0, 0, 0]
array([False,  True,  True, False])

You are prompted to use any() or all() and that's quite a helpful hint.系统会提示您使用 any() 或 all(),这是一个非常有用的提示。 All(something) means all elements of something you want to check has to be true. All(something) 表示您要检查的某物的所有元素都必须为真。 So in your case:所以在你的情况下:

>>> np.all(opponentsActions == [0, 0, 0, 0])
False

You are comparing a numpy array with Python list, that won't work, a quick workaround can be converting the numpy array to python list using tolist() where you are comparing, it will work that way, have a look: You are comparing a numpy array with Python list, that won't work, a quick workaround can be converting the numpy array to python list using tolist() where you are comparing, it will work that way, have a look:

history = np.array([[0, 0, 1, 1],[0, 0, 0, 0]])
opponentsActions = history[1]
print(opponentsActions)
if opponentsActions.tolist() == [0, 0, 0, 0]:
     print("nice")

Or you can use np.all as suggested by SebaLenny.或者您可以按照 SebaLenny 的建议使用 np.all。

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

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