# 如何让列表内的元素前后相加生成新的元素？

``data = [1, 2, 3, 4]``

``````data1 = [1, 3, 5, 7] # 与前面的一个元素相加
data2 = [1, 3, 6, 10] # 与前面的一个元素累计相加``````

### 回答：

``data = [1, 2, 3, 4]``

``````from itertools import accumulate

data1 = [v + (data[i-1] if i > 0 else 0) for i, v in enumerate(data)]
data2 = list(accumulate(data))

print(data1)
print(data2)``````

``````[1, 3, 5, 7]
[1, 3, 6, 10]``````

### 回答：

``````data1= data[:1] + [x+y for x,y in zip(data[1:],data[:-1])]
data1= data[:1] + [sum(data[x:x+2]) for x in range(len(data)-1)]
data2= [sum(data[:x]) for x in range(1,len(data)+1)]``````

data1 其实你也可以用带 if else的列表推到而不用单独处理第一个。
`data1= [sum(data[x-1:x+1]) if x>0 else data[0] for x in range(0,len(data))]`

### 回答：

``````pre = 0
def foo(x):
global pre
y = x + pre
pre = x
return y

subtotal = 0
def bar(x):
global subtotal
subtotal = x + subtotal
return subtotal

data = [1, 2, 3, 4]

data1 = list(map(foo, data))

data2 = list(map(bar, data))

print(data1, data2)``````

### 回答：

``````from itertools import accumulate
data = [1, 2, 3, 4]

data1 = [x + y for x, y in enumerate(data)]
data2 = list(accumulate(data))

print(data1)
print(data2)``````