Python对两个数字之间的元素进行求和

时间:2022-02-09 14:09:21

I'm sure this is very simple. I've searched google and here and not found the specific answer

我相信这很简单。我搜索了谷歌,但没有找到具体的答案。

a = rnd.randn(100)
print np.sum(a)

gives sum of elements in a

给出a元素的和

np.sum(a[a>0.])

gives sum of elements greater than 0

给出大于0的元素的和

print np.sum((a < 2.0) & (a > -2.0))

ok so this returns the number of elements between 2 and -2.

它返回2和-2之间的元素个数。

how do I get the sum of the elements between2 and -2??? I've tried lots of things for example

如何得到2和-2之间元素的和?我尝试过很多东西

np.sum(a[a >0.] & a[a<1.])

etc and can't find the correct way to do it :-(

不能找到正确的方法去做。

2 个解决方案

#1


4  

& is a bitwise operator and doesn't give you the proper result, instead you need to use np.logical_and to get a mask array. Then you can pass it as the index to the array in order to get the desire items, then pass it to the sum:

&是位运算符,并没有给出正确的结果,而是需要使用np。并获取掩码数组。然后您可以将它作为索引传递给数组,以便获得所需的项,然后将它传递给sum:

In [9]: a = np.arange(-10, 10)

In [10]: a[np.logical_and(a>-2,a<2)]
Out[10]: array([-1,  0,  1])

In [11]: a[np.logical_and(a>-2,a<2)].sum()
Out[11]: 0

#2


1  

You could do it in just in a very basic direct way, something like:

你可以用一种非常简单的方式来做,比如:

function getSum(numArray, lowVal, highVal):
    mySum = 0
    for i in range(len(numArray)):
        if(numArray[i] >= lowVal and numArray[i] <= highVal):
             mySum = mySum + numArray[i]

    return mySum

yourAnswer = getSum(a, -2, 2)

#1


4  

& is a bitwise operator and doesn't give you the proper result, instead you need to use np.logical_and to get a mask array. Then you can pass it as the index to the array in order to get the desire items, then pass it to the sum:

&是位运算符,并没有给出正确的结果,而是需要使用np。并获取掩码数组。然后您可以将它作为索引传递给数组,以便获得所需的项,然后将它传递给sum:

In [9]: a = np.arange(-10, 10)

In [10]: a[np.logical_and(a>-2,a<2)]
Out[10]: array([-1,  0,  1])

In [11]: a[np.logical_and(a>-2,a<2)].sum()
Out[11]: 0

#2


1  

You could do it in just in a very basic direct way, something like:

你可以用一种非常简单的方式来做,比如:

function getSum(numArray, lowVal, highVal):
    mySum = 0
    for i in range(len(numArray)):
        if(numArray[i] >= lowVal and numArray[i] <= highVal):
             mySum = mySum + numArray[i]

    return mySum

yourAnswer = getSum(a, -2, 2)