这是一个简单列表中的示例
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()