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

我有一个列表,想要将 index(-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]

new_list[0] = 0+ list[0]  = 0+ (-2) = -2

new_list[1] = list[0] + list[1] = (-2) + (-2) = -4

new_list[2] = list[1] + list[2] = (-2)+ (-1) = -3

new_list[3] = list[2] + list[3] = (-1)+ (1) = 0


Basically new_list[index] = list[index -1] + list[index]


智慧大石
浏览 146回答 3
3回答

红颜莎娜

如果我正确理解您的要求,您可以使用pandas. 例如:import pandas as pd# Create a pandas Series of valuess = 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]

慕侠2389804

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]

慕虎7371278

您必须迭代列表并添加数字,如下所示:list = [-2, -2, -1, 1, -1, 1, 3, 5, 6, -2, -1, 0, -2, -1, -2, 2]new_list = list[0] # We just take the first element of the list, because we don't add anythingfor number, element in enumerate(list[1:]):    new_list.append(element + list[number - 1])或者更pythonic的方式:new_list = [list[0]].extend([element + list[number - 1] for number, element in enumerate (list[1:])
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python