简体   繁体   English

列表内数组中元素的总和

[英]Sum of elements within an array within list

I'm trying to calculate the np.sum of the elements within each array. 我正在尝试计算每个数组中元素的np.sum。 I tried in stead of np.sum(outcome_list[0] == 'H' to just leave it as np.sum(outcome_list[j] == 'H' so that each "list" would have its own data set on the total number of heads, but it didn't like it. The bigger question is, how would I construct an array with a given base list and the action to be done in each element of that list? 我尝试代替np.sum(outcome_list[0] == 'H'只是将其保留为np.sum(outcome_list[j] == 'H'以便每个“列表”将在头的总数,但不喜欢它。更大的问题是,如何构造具有给定基本列表的数组以及在该列表的每个元素中要执行的操作?

在此处输入图片说明

EDIT: 编辑:

the throw_a_coin definition throw_a_coin定义

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

trials (as shown above) is the set to be acted upon 试验(如上所示)是要执行的任务

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)

EDIT 2: 编辑2:

problem resolved with the one shown below, however I'm getting more than 13 numbers for "probabilities" - it seems that the system is running through the trials list more than once. 问题如下所示,但是我获得的“概率”超过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)

尝试这个:

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

You were nearly there! 你快到了! You just needed to replace 您只需要更换

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

with

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

Here is the complete answer: 这是完整的答案:

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)

如果output_list是一个numpy数组,并且矩阵中的每一行代表每个试验,则可以按如下所示的有效方式获得总和:

head_sum = output_list.sum(axis=1)

I would use a list comprehension followed by a len call. 我会先使用列表推导,然后再调用len

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

DISCLAIMER : I have zero experience with Numpy. 免责声明 :我对Numpy的经验为零。 However, this would be the general Pythonic way to do it without resorting to count . 但是,这将是不使用count的通用Pythonic方法。

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

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