2017-09-03 81 views
0

我想要計算每個數組內的元素的np.sum。我試圖用np.sum(outcome_list[0] == 'H'來代替np.sum(outcome_list[j] == 'H',以便每個「列表」都有自己的數據集,但它不喜歡它。更大的問題是,我將如何構建一個具有給定基本列表的數組以及要在該列表的每個元素中執行的操作?列表中的元素的總和

enter image description here

編輯:

的throw_a_coin定義

def throw_a_coin(N): 
    return np.random.choice(['H','T'], size=N) 
N =40 

試驗(如上圖所示)是組可

for i in trials: 
    throws = throw_a_coin(i) 
    outcome_list.append(throws) 

for j in outcome_list: 
    print("Number of Heads:", np.sum(outcome_list[0] == 'H')) 
    print (j) 
0至被作用

編輯2:

問題,如下所示的解決,但是我得到超過13號的「概率」 - 看來,該系統通過試驗運行多於一次。

def throw_a_coin(N): 
    return np.random.choice(['H','T'], size=N) 

trials = [10, 30, 50, 70, 100, 130, 170, 200, 500, 1000, 2000, 5000, 10000] 

for i in trials: 
    throws = throw_a_coin(i) 
    outcome_list.append(throws) 

probabilities = [] 

for j in outcome_list: 
    print("Number of Heads:", np.sum(j == 'H')) 
    print("Number of Throws:", len(j)) 
    print("p = Number of Heads/Total Throws:", (np.sum(j == 'H'))/len(j)) 
    probabilities.append((np.sum(j =='H'))/len(j)) 
    print (j) 
    print("\n") 

print(probabilities) 
+0

您是否想要統計頭數? – Rishav

+2

你能否附上代碼而不是代碼的照片? –

+0

@Rishav - 是的,計算每次試驗的頭數 – aiwan

回答

1

你快到了!你只需要與

print("Number of Heads:", np.sum(j == 'H')) 

更換

print("Number of Heads:", np.sum(outcome_list[0] == 'H')) 

下面是完整的答案:

trials = [10, 30, 50, 70, 100, 130, 170, 200, 500, 1000, 2000, 5000, 10000] 

N =40 
def throw_a_coin(N): 
    return np.random.choice(['H','T'], size=N) 

outcome_list = [] 
for i in trials: 
    throws = throw_a_coin(i) 
    outcome_list.append(throws) 

for j in outcome_list: 
    print("Number of Heads:", np.sum(j == 'H')) 
    print (j) 
+0

我還在問題中添加了「編輯2」 - 它似乎正在貫穿「試驗」不止一次? – aiwan

0

如果output_list將是一個numpy的陣列,如果在矩陣中的每一行代表每次試驗中,可以以高效的方式獲得的總和如下:

head_sum = output_list.sum(axis=1) 
0

我會用一個列表理解後跟一個len電話。

for j in outcome_list: 
    print("Number of Heads:", len([x for x in j if x == 'H']) 
    print (j) 

免責聲明:我有NumPy的零距離體驗。然而,這將是一般的Pythonic方法,而不訴諸於count

+0

這是相當不錯的,但是我會推薦'sum(1,如果x =='H',則爲1)通過使用生成器理解,我們避免實際構建'H'列表。這是一個很小的差異,但我只是想我會提到它。 –