简体   繁体   English

将列表的元素加在一起 python

[英]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.除了在 new_lst 中 r1 被命名为“x1”,r1+r2 被命名为“x2 等。

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;然后通过说“n”是否在 0 和 x1、x1 和 x1+x2 等之间来引用此列表; 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.下面的代码确实创建了 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?为什么不直接用numpy中的累加和function呢?

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:这可能看起来有点不切实际,但它确实包括定义您在帖子中提到的 x1、x2、x3 和 x4:

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.但不推荐这样做,因为它使用 exec,这被认为是一种不好的做法,因为它通常被滥用来执行不需要它的任务,从而导致潜在的安全问题和通常糟糕的编程。

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.如果可能,只需手动定义变量,或者,还有一种方法让 python 将它们全部写入一个单独的文件,以便您可以将其复制并粘贴到您的主脚本中。

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:它通过简单的列表分配创建 x1 到 x4:

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.也许您正在使用单个变量,而dict会更好地为您服务。

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

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