简体   繁体   中英

How to add list together

I'm trying to figure out a question and I'm getting confused. Basically I have a list and it's supposed to represent a bank statement. I'm trying to add the list together so the negative numbers, which is supposed to represent withdrawl, is added together and the positive numbers are added together to represent the deposits. So far I got

def statement(l):
    deposit = 0
    withdrawl = 0
    for a in l:
        a = sum(l)
    for b in l:
        if b == -b:
            b = sum(b)        
    return [a,-b]

but when I do statement([30.95,-15.67,45.56,-55.00,43.78]) it returns [49.620000000000005, -43.78] when it is supposed to return [120.29,-70.67] can someone help?

Thanks!

The following seems to do it:

In [1]: def statement(l):
   ...:     pos, neg = 0, 0
   ...:     for a in l:
   ...:         if a > 0: pos += a
   ...:         else: neg += a
   ...:     return pos, neg
   ...: 

In [2]: statement([30.95,-15.67,45.56,-55.00,43.78])
Out[2]: (120.29, -70.67)

It returns a tuple rather than a list , which seems more logical as the length is fixed.


Here's a couple of comments on your attempt:

for a in l:
    a = sum(l)

This will lead to the sum of all elements of l being calculated len(l) times, which doesn't make much sense. To get a sum, just do a = sum(l) once.

if b == -b: - you probably expect this to check if a number is negative, but in fact it checks if b equals zero, because zero is the only x so that x == -x . You want if b < 0: .


I checked which answer is faster on CPython 3.3, and unsurprisingly this one is about 2 times faster on the example given: 2.3 us per loop vs 5.98 us per loop .

This should do what you want:

def statement(l):
    pos = sum(i for i in l if i > 0)
    neg = sum(i for i in l if i < 0)
    return pos, neg

Your mistake is that you try to assign to iteration variables. If you want to accumulate a value, define it as 0 first outside of the for loop then add on to that with each step.

At the end of the loop, a contains the sum of all the elements in l , and b contains the last element in l , because the final check always fails and b is never overwritten (which explains the result you got).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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