列表中数组内的元素总和

时间:2017-09-03 05:02:39

标签: python arrays list sum

我试图计算每个数组中元素的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)

编辑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)

4 个答案:

答案 0 :(得分:1)

试试这个:

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

答案 1 :(得分:1)

你快到了!你只需要替换

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

print("Number of Heads:", np.sum(j == '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)

答案 2 :(得分:0)

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

head_sum = output_list.sum(axis=1)

答案 3 :(得分:0)

我会使用列表推导,然后是len调用。

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

免责声明 :我对Numpy没有经验。但是,如果不诉诸count,这将是一般的Pythonic方法。