如何修复:包含多个元素的数组的真值不明确。使用a.any()或a.all()

2024-09-30 20:20:29 发布

您现在位置:Python中文网/ 问答频道 /正文

我正试着计算横梁的弯曲度,但我得到了一个错误。我是新的编码,所以我不知道什么是错的。如果我只放整数或浮点数是工作的,但当我插入数组我得到这个错误

def poves(x):
    eta1 = a/L
    eta2 = (a+b)/L
    zeta = x/L
    E = 210e3 #MPA
    F1 = Ft_1
    F2 = Ft_3
    Iy = 50**4*np.pi/64 ##mm
    if(0<=x<=a):
        return F1 * L * zeta*(1-eta2)/(E*Iy)
    elif(a<x<=L):
        return F1 * L * eta2*(1-zeta)/(E*Iy)
    else:
        print(f'Nope')
ValueError                                Traceback (most recent call last)
<ipython-input-149-e30266137f00> in <module>
----> 1 poves(x)

<ipython-input-148-290878c57829> in poves(x)
      7     F2 = Ft_3
      8     Iy = 50**4*np.pi/64 ##mm
----> 9     if(0<=x<=a):
     10         return F1 * L * zeta*(1-eta2)/(E*Iy)
     11     elif(a<x<=L):

ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

Tags: returnif错误nppif2f1mm
1条回答
网友
1楼 · 发布于 2024-09-30 20:20:29

正如ValueError所指出的,您的x是一个数组。在这种情况下,请尝试使用all,如下所示:

if np.all((0<=x) & (x<=a)):

示例

a = 13
x = np.array([1, 2, 3, 4, 12, 4, 0.1, 3, 9])

if np.all((0<=x) & (x<=a)):
    print ("Condition fulfilled")
else:    
    print ("Condition not fulfilled")

# Condition fulfilled

对于list,可以通过迭代x的元素来比较每个元素。你知道吗

示例

a = 10
x = [1, 2, 3, 4, 12, 4, 0.1, 3, 9]

if all(0<=i<=a for i in x):
    print ("Condition fulfilled")
else:    
    print ("Condition not fulfilled")

# Condition not fulfilled

a = 15
x = [1, 2, 3, 4, 12, 4, 0.1, 3, 9]

if all(0<=i<=a for i in x):
    print ("Condition fulfilled")
else:    
    print ("Condition not fulfilled")

# Condition fulfilled

相关问题 更多 >