将一个元素从列表添加到下一个,然后添加到下一个等

时间:2013-08-14 16:55:11

标签: python list

以下是一个简单列表中的示例

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()

6 个答案:

答案 0 :(得分: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(...)将数组转回列表。

答案 1 :(得分: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)

答案 2 :(得分: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

答案 3 :(得分: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

答案 4 :(得分:0)

这是另一个版本:

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

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

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

输出:

7
16
28
78

答案 5 :(得分: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
相关问题