将列表的编号添加到列表的第一个编号

b1uwtaje  于 2021-07-13  发布在  Java
关注(0)|答案(5)|浏览(401)

我有以下清单:

list_1= [2.03898103, 2.23708741, 1.68221573, 1.12352885, 0.56227805]

我想把第一个数字加到新的列表中,像这样:

list_2=[]
list_2[0]=list_1[0]
list_2[1]=list_1[0]+list_1[1]
list_2[2]=list_1[0]+list_1[1]+list_1[2]
list_2[3]=list_1[0]+list_1[1]+list_1[2]+list_1[3]
list_2[4]=list_1[0]+list_1[1]+list_1[2]+list_1[3]+list_1[4]

你知道我怎么用for-loop或者更实用的东西来做这个吗?

hmae6n7t

hmae6n7t1#

你可以用 itertools.accumulate :

from itertools import accumulate

list_1 = [2.03898103, 2.23708741, 1.68221573, 1.12352885, 0.56227805]
list_2 = list(accumulate(list_1))
print(list_2)

印刷品:

[2.03898103, 4.2760684399999995, 5.95828417, 7.08181302, 7.64409107]
1tuwyuhd

1tuwyuhd2#

如果你想要一个简短的答案,你也可以使用生成器:

list_2 = [sum(list_1[:(i+1)]) for i in range(len(list_1))]
gv8xihay

gv8xihay3#

list_1 = [2.03898103, 2.23708741, 1.68221573, 1.12352885, 0.56227805]
list_2 = []
j = 0.
for i in range(0,len(list_1)):
    j = j + list_1[i]
    list_2.append(j)
print(list_2)
exdqitrt

exdqitrt4#

你的问题中已经标记了numpy,所以使用 numpy.cumsum :

>>> import numpy as np
>>> list_1 = np.array([2.03898103, 2.23708741, 1.68221573, 1.12352885, 0.56227805])
>>> np.cumsum(list_1)
array([2.03898103, 4.27606844, 5.95828417, 7.08181302, 7.64409107])
jogvjijk

jogvjijk5#

可以使用多个for循环。

list_1 = [2.03898103, 2.23708741, 1.68221573, 1.12352885, 
0.56227805]
list_2 = []

for i in range(0, 4):
     for j in range(0, i):
          list_2[i] += list_1[j]

相关问题