簡體   English   中英

ValueError:具有多個元素的數組的真值不明確。 在模擬觀察時使用 a.any() 或 a.all()

[英]ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all() while simulation observations

我想模擬來自均勻分布和二維正態分布的一些觀察結果並計算平均值,但我得到錯誤值錯誤ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all() 在第 5 行ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all() ,但是當我將A != None更改為A.any() == True我得到AttributeError: 'list' object has no attribute 'any'我怎么能解決這個問題?

import numpy as np
import random

def getmean(A):
    if A != None:
        return np.sum(A)/len(A)
    else:
        return 0


for n in [1, 50, 1000]:
    unifs = []
    normals = []

    # uniform
    for i in range(n):
        unifs.append(random.random())

    # normal
    for i in range(n):
        normals.append(np.array([np.random.normal(0, 1),
                                 np.random.normal(0, 1)]))
    normals = np.array(normals)

    print("n:", n, "normal mean:", getmean(unifs))
    print("n:", n, "unif mean:", getmean(normals))  

    

我明白你為什么使用if A:= None: comparison 或為什么你需要any()來達到你在問題中所說的目的,但你只需要檢查 A 是否有任何成員,為此目的,你可以使用任何以下方法代替:

...
    if A:
...

或者

...
    if len(A):
...

或者

...
    if len(A) != 0:
...

但是無論如何,我在這里為您解釋any() function。

python 中的list或其他數據結構本身沒有.any()方法。 有一個名為any()的 function,您可以將其用於 python 中的所有可迭代對象,例如listtuple等,您可以通過以下方式使用它:

sample_list = [0, 1, 2]
print(any(sample_list))
# prints: True

sample_list2 = [] # or [0, 0, 0]
print(any(sample_list2))
# prints: False

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM