Python 生成連續元素差值列表


在這篇文章中,我們將看到如何找出給定列表中每對元素的兩個連續元素之間的差值。該列表僅包含數字元素。

帶索引

使用元素的索引和 for 迴圈,我們可以找出連續元素對之間的差值。

示例

 即時演示

listA = [12,14,78,24,24]
# Given list
print("Given list : \n",listA)
# Using Index positions
res = [listA[i + 1] - listA[i] for i in range(len(listA) - 1)]
# printing result
print ("List with successive difference in elements : \n" ,res)

輸出

執行以上程式碼,會返回以下結果 -

Given list :
[12, 14, 78, 24, 24]
List with successive difference in elements :
[2, 64, -54, 0]

帶切片

切片是另一種技術,其中我們從列表中切出連續元素對,然後應用 zip 函式獲得結果。

示例

 即時演示

listA = [12,14,78,24,24]
# Given list
print("Given list : \n",listA)
# Using list slicing
res = [x - y for y, x in zip(listA[: -1], listA[1 :])]
# printing result
print ("List with successive difference in elements : \n" ,res)

輸出

執行以上程式碼,會返回以下結果 -

Given list :
[12, 14, 78, 24, 24]
List with successive difference in elements :
[2, 64, -54, 0]

帶 sub

還可透過 map 函式使用 operators 模組中的 sub 方法。我們再次使用切片技術切出兩個連續的元素對。

示例

 即時演示

import operator
listA = [12,14,78,24,24]
# Given list
print("Given list : \n",listA)
# Using operator.sub
res = list(map(operator.sub, listA[1:], listA[:-1]))
# printing result
print ("List with successive difference in elements : \n" ,res)

輸出

執行以上程式碼,會返回以下結果 -

Given list :
[12, 14, 78, 24, 24]
List with successive difference in elements :
[2, 64, -54, 0]

更新於: 09-07-2020

395 次瀏覽

開啟你的 職業生涯

完成課程並獲得認證

入門
廣告
© . All rights reserved.