列表中交替元素求和 (Python)
本文中給定一個數字列表,我們將計算該列表中交替元素的總和。
使用列表切片和範圍
使用 range 函式以及 length 函式獲取要相加的元素數量,計算每一個偶數。
示例
listA = [13,65,78,13,12,13,65] # printing original list print("Given list : " , str(listA)) # With list slicing res = [sum(listA[i:: 2]) for i in range(len(listA) // (len(listA) // 2))] # print result print("Sum of alternate elements in the list :\n ",res)
輸出
執行以上程式碼,得到以下結果 −
Given list : [13, 65, 78, 13, 12, 13, 65] Sum of alternate elements in the list : [168, 91]
使用範圍和 %
使用百分號運算子分離奇數和偶數位置的數字。然後將元素新增到新空列表的相應位置。最後給出顯示奇數位置的元素總和和偶數位置的元素總和的列表。
示例
listA = [13,65,78,13,12,13,65] # printing original list print("Given list : " , str(listA)) res = [0, 0] for i in range(0, len(listA)): if(i % 2): res[1] += listA[i] else : res[0] += listA[i] # print result print("Sum of alternate elements in the list :\n ",res)
輸出
執行以上程式碼,得到以下結果 −
Given list : [13, 65, 78, 13, 12, 13, 65] Sum of alternate elements in the list : [168, 91]
廣告