Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/285.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何将数组的每个元素除以数组的和?_Python_Arrays_Numpy - Fatal编程技术网

Python 如何将数组的每个元素除以数组的和?

Python 如何将数组的每个元素除以数组的和?,python,arrays,numpy,Python,Arrays,Numpy,我有以下数组: propensity = [32. 0. 0.] 我计算了数组的和,如下所示: a0 = sum(propensity) 我试图计算数组中每个元素在数组总和上的分数,并编写了以下函数: def prob_rxn_fires(propensity, a0): for x in propensity: print("propensity:\n", x) prob = x/a0 print("Prob reaction fires:\n", prob)

我有以下数组:

propensity = [32.  0.  0.]
我计算了数组的和,如下所示:

a0 = sum(propensity)
我试图计算数组中每个元素在数组总和上的分数,并编写了以下函数:

def prob_rxn_fires(propensity, a0):
for x in propensity:
    print("propensity:\n", x)  
    prob = x/a0  
print("Prob reaction fires:\n", prob)      
return prob
我希望函数为每个数组元素返回三个分数,此时它只返回0。我认为这是因为当它遍历数组并到达return语句时,它只返回它计算的最后一个值,即0/32=0.0。我还需要返回前2个值,但我不确定如何修复此问题


干杯

使用
numpy
怎么样

import numpy as np

propensity = np.array([32.0,  0.0,  0.0])
propensity/sum(propensity)
输出:
你可以做的很简单

propensity = [32.,  0.0,  0.0]
a0 = sum(propensity)
propensity = [x/a0 for x in propensity]
print(propensity)
输出

[1.0, 0.0, 0.0] 

这种技术可能会遇到低级问题,因为
倾向
iterable正在并行迭代和编写。考虑修改。什么级别的低级别问题?我认为只需要添加检查除法为零,以及您的解决方案为什么要为如此简单的任务导入numpy,因为我记不清所有细节。根据我的记忆,当Python将iterable分配给哈希表时,有时循环将不会继续,因为它认为下一个值是已经看到的,因此过早退出—这是由于哈希值的存储顺序。建议:只需将列表comp输出分配给另一个变量。
[1.0, 0.0, 0.0]