亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何對列表中的前一個值求和

如何對列表中的前一個值求和

智慧大石 2022-06-02 18:09:36
我有一個列表,想要將 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) = -2new_list[1] = list[0] + list[1] = (-2) + (-2) = -4new_list[2] = list[1] + list[2] = (-2)+ (-1) = -3new_list[3] = list[2] + list[3] = (-1)+ (1) = 0Basically new_list[index] = list[index -1] + list[index]
查看完整描述

3 回答

?
紅顏莎娜

TA貢獻1842條經驗 獲得超13個贊

如果我正確理解您的要求,您可以使用pandas. 例如:


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]



查看完整回答
反對 回復 2022-06-02
?
慕俠2389804

TA貢獻1719條經驗 獲得超6個贊

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]


查看完整回答
反對 回復 2022-06-02
?
慕虎7371278

TA貢獻1802條經驗 獲得超4個贊

您必須迭代列表并添加數字,如下所示:


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 anything


for 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:])



查看完整回答
反對 回復 2022-06-02
  • 3 回答
  • 0 關注
  • 160 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號