使用numpy数组进行计算时放置条件 [英] Placing a condition while calculating using numpy array

查看:64
本文介绍了使用numpy数组进行计算时放置条件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下是一小段代码,由于某种原因,该代码会不断生成以下值错误消息:ValueError:具有多个元素的数组的真值不明确.使用a.any()或a.all().

Below is a short piece of code that for some reason keeps generating the following value error message: ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all().

import numpy as np
p=np.array([1,2,3])
q=np.array([4,5,5])

while p + q==7:
        try:
            assert p.any()
            assert q.any()
        except AssertionError:
            print('(p + q)<=6')
        print  (p + q)

我已经尝试了p.anyp.all,仍然收到相同的错误消息.有什么建议?谢谢.

I have tried both p.any and p.all, still getting the same error message. Any suggestions? Thanks.

推荐答案

您的问题是pq分别具有三个元素,因此p + q == 7也将具有三个元素.对于while循环,您需要一些可以解释为True或False的东西-错误告诉您,没有更多信息就不能将三个元素解释为True或False:这是模棱两可的.如果您希望所有元素都等于7,请使用

Your problem is that p and q have three elements each, so p + q == 7 will also have three elements. For the while loop, you need something that can be interpreted as True or False - the error is telling you that three elements can't be interpreted as True or False without more information: it's ambiguous. If you want all of the elements to be equal to 7, use

while np.all(p + q == 7):

如果您希望它们中的任何一个相等,请使用

if you want any of them to be equal, use

while np.any(p + q == 7):

这篇关于使用numpy数组进行计算时放置条件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆