0

这是一个简单列表中的示例

mylist = [2,5,9,12,50]

我想将第一个元素(在本例中为 2)添加到它旁边的元素中。它是数字 5。结果 (2+5=7) 应添加到下一个元素,在我的示例中为数字 9。结果应添加到下一个元素等...

我现在有这个片段正在工作,但必须有一个更简单更好的方法:

newlist = [5, 9, 12 , 50]
counts = 0
a = 2
while (counts < 5):
    a = a + mylist[n]
    print a
    counts = counts + 1

输出是:

7
16
28
78

下一个片段:

mylist = [2, 5, 9, 12, 50]
lines_of_file = [4, 14, 20, 25, 27]
sum_list = []
outcome = 0

for element in mylist:
    outcome = outcome + element
    sum_list.append(outcome)

fopen = ('test.txt', 'r+')
write = fopen.readlines()

for element, line in zip(sum_list, lines_of_file):
    write[line] = str(element)

fopen.writelines()
fopen.close()
4

6 回答 6

1

你可以做这样简单的事情:

>>> mylist = [2,5,9,12,50]
>>> 
>>> total = 0  # initialize a running total to 0
>>> for i in mylist:  # for each i in mylist
...     total += i  # add i to the running total
...     print total  # print the running total
... 
2
7
16
28
78

numpy这样做有一个很好的功能,即cumsum()

>>> import numpy as np
>>> np.cumsum(mylist)
array([ 2,  7, 16, 28, 78])

您可以使用list(...)将数组转回列表。

于 2013-08-14T16:59:22.830 回答
0

用于sum()将序列的所有值相加:

>>> sum([2,5,9,12,50])
78

但是如果你想保持一个运行总数,只需遍历你的列表:

total = 2
for elem in newlist:
    total += a
    print total

这也可以用来建立一个列表:

total = 2
cumsum = []
for elem in newlist:
    total += a
    cumsum.append(total)
于 2013-08-14T16:57:23.917 回答
0

这是可能的解决方案之一:

#!/usr/local/bin/python2.7

mylist = [2,5,9,12,50]
runningSum = 0

for index in range(0,len(mylist)):
    runningSum = runningSum + mylist[index]
    print runningSum
于 2013-08-14T17:01:56.137 回答
0

如果您想将其写入文件中的特定位置,请尝试以下操作:

假设您有一个numbers.txt文件,有 10 行,如下所示:

0
0
0
0
0
0
0
0
0
0

然后使用这个:

original_list = [1, 3, 5, 7, 9]
lines_to_write = [2, 4, 6, 8, 10]  # Lines you want to write the results in
total = 0
sum_list = list()

# Get the list of cumulative sums
for element in original_list:
    total = total + element
    sum_list.append(total)
# sum_list = [1, 4, 9, 16, 25]

# Open and read the file
with open('numbers.txt', 'rw+') as file:
    file_lines = file.readlines()
    for element, line in zip(sum_list, lines_to_write):
        file_lines[line-1] = '{}\n'.format(element)
    file.seek(0)
    file.writelines(file_lines)

然后你会numbers.txt变成这样:

0
1
0
4
0
9
0
16
0
25
于 2013-08-14T17:16:04.340 回答
0

这是另一个版本:

newlist = [2,5,9,12,50]

for i in range(1,len(newlist)):
    print sum(newlist[:i+1])

请注意,它不包括2您想要的 , 。它可能会一遍又一遍地计算总和(我不知道编译器有多聪明)。

输出:

7
16
28
78
于 2013-08-14T17:19:56.617 回答
0

如果您不想显示列表中的第一项(编号 2),那么此解决方案将执行此操作:

mylist = [2,5,9,12,50]

it = iter(mylist)
total = it.next() # total = 2, first item
for item in it:
    total += item
    print total
于 2013-08-14T17:40:49.560 回答