简体   繁体   English

Python总和两个数字之间的元素

[英]Python sum elements between two numbers

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 给出一个元素的总和

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??? 如何得到2和-2之间的元素之和??? I've tried lots of things for example 我试过很多东西

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

etc and can't find the correct way to do it :-( 等,找不到正确的方法:-(

& 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. &是一个按位运算符,并没有给你正确的结果,而是你需要使用np.logical_and来获得一个掩码数组。 Then you can pass it as the index to the array in order to get the desire items, then pass it to the sum : 然后你可以将它作为索引传递给数组,以获得所需的项目,然后将其传递给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

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)

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

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