Python 如何对列表中的前一个值求和

Python 如何对列表中的前一个值求和,python,sum,Python,Sum,我有一个列表,希望将索引(-1)的值与整个列表的当前值索引相加 list = [-2, -2, -1, 1, -1, 1, 3, 5, 6, -2, -1, 0, -2, -1, -2, 2] 预期产出: new_list =[-2,-4,-3, 0, 0, 0, 4, 8, 11, 4, -3, -1, -2, -3, -3, 0] 以上是您的任务的解决方案。您必须在列表上迭代并添加如下数字: list=[-2、-2、-1、1、-1、1、3、5、6、-2、-1、0、-2、-1、-2、2]

我有一个列表,希望将索引(-1)的值与整个列表的当前值索引相加


list = [-2, -2, -1, 1, -1, 1, 3, 5, 6, -2, -1, 0, -2, -1, -2, 2]
预期产出:

new_list =[-2,-4,-3, 0, 0, 0, 4, 8, 11, 4, -3, -1, -2, -3, -3, 0]

以上是您的任务的解决方案。

您必须在列表上迭代并添加如下数字:

list=[-2、-2、-1、1、-1、1、3、5、6、-2、-1、0、-2、-1、-2、2]
new_list=list[0]#我们只取列表的第一个元素,因为我们不添加任何内容
对于数字,枚举中的元素(列表[1:]):
新增列表。追加(元素+列表[编号-1])
或者用一种更为通灵的方式:

new_list=[list[0]]。扩展([element+list[number-1]表示数字,枚举中的元素(list[1:])

如果我正确理解您的需求,您可以使用
熊猫
轻松完成这项工作。例如:

import pandas as pd

# Create a pandas Series of values
s = pd.Series([-2, -2, -1, 1, -1, 1, 3, 5, 6, -2, -1, 0, -2, -1, -2, 2])
# Add the current value in the series to the 'shifted' (previous) value.
output = s.add(s.shift(1), fill_value=0).tolist()
# Display the output.
print(output)
输出:

[-2.0, -4.0, -3.0, 0.0, 0.0, 0.0, 4.0, 8.0, 11.0, 4.0, -3.0, -1.0, -2.0, -3.0, -3.0, 0.0]

您的输入和预期输出似乎与您描述的内容不匹配
list(map(sum,zip(l,l[1:]))
new_list=[list[x]+list[x-1]if x!=0,否则列表[x]表示范围内的x(len(list))]
?在我看来,这与请求的输出不匹配。实际上,他犯了一个错误,包括了数组的第一个值。因为没有这样一个和来获得那个数字。另一方面,用列表的第一个元素初始化空数组是最简单的解决方案。没有必要提及。在我看来这与请求的输出不匹配
list1 = [-2, -2, -1, 1, -1, 1, 3, 5, 6, -2, -1, 0, -2, -1, -2, 2]
new_list=[list1[0]]
for i in range(len(list1)-1):
    value=list1[i]+list1[i+1]
    new_list.append(value)


print(new_list)
Output:[-2,-4,-3, 0, 0, 0, 4, 8, 11, 4, -3, -1, -2, -3, -3, 0]
import pandas as pd

# Create a pandas Series of values
s = pd.Series([-2, -2, -1, 1, -1, 1, 3, 5, 6, -2, -1, 0, -2, -1, -2, 2])
# Add the current value in the series to the 'shifted' (previous) value.
output = s.add(s.shift(1), fill_value=0).tolist()
# Display the output.
print(output)
[-2.0, -4.0, -3.0, 0.0, 0.0, 0.0, 4.0, 8.0, 11.0, 4.0, -3.0, -1.0, -2.0, -3.0, -3.0, 0.0]