简体   繁体   中英

Add elements of a list together python

I have this list

r1 = 2
r2 = 4
r3 = 5
r4 = 9 
lst = [r1, r2, r3, r4]

I want to create a new list which looks like this:

new_lst = [r1, r1+r2, r1+r2+r3, r1+r2+r3+r4]

Except in the new_lst r1 is named "x1", r1+r2 named "x2 etc.

I'm currently doing this using:

new_lst = []
new_lst.append(sum(lst[0:1]))
new_lst.append(sum(lst[0:2]))
new_lst.append(sum(lst[0:3]))    
new_lst.append(sum(lst[0:4]))     

And then refer to this list by saying if "n" is between 0 and x1, x1 and x1+x2 etc; print yie

 if n >=0 and n <= new_lst[0]:
      print(y)
 elif n >=new_lst[0] and n <= new_lst[1]:
      print(z)

The code below does create the new_list.

lst = [2,4,5,9]
new_lst = [sum(lst[0:i+1]) for i,v in enumerate(lst)]

Why not simply use the cumulative sum function in numpy?

import numpy as np

print(np.array([2,4,5,9]).cumsum())

This might seem a bit unpractical, but it does include defining the x1, x2, x3 and x4 you mentioned in your post:

r1 = 2
r2 = 4
r3 = 5
r4 = 9 
lst = [r1, r2, r3, r4]
new_lst = []
s = ''
for n in range(1,len(lst)+1):
    s += f'+r{n}'
    exec(f'x{n}='+s)
    new_lst.append(eval(f'x{n}'))

print(new_lst)

This is not recommended though, because it uses exec, which is considered a bad practice because it's generally abused to do a task where it isn't needed, leading to potential security issues and generally bad programming.

If possible, just define the variables manually, or, there's also a way to let python write them all into a separate file so you can copy and paste it into your main script.

As best as I can understand your question, I believe the following does what you describe. It creates x1 through x4 via simple list assignment:

r1 = 2
r2 = 4
r3 = 5
r4 = 9

array = [r1, r2, r3, r4]

x1, x2, x3, x4 = [sum(array[0:n + 1]) for n in range(len(array))]

if 0 <= n <= x1:
    print(y)
elif x1 <= n <= x2:
    print(z)

The fact that you need to do this at all suggests to me you've gone down a wrong path somewhere. Perhaps you're using individual variables where a dict would serve you better.

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