Python 生成连续元素差异列表
pythonserver side programmingprogramming更新于 2025/7/31 9:16:17
在本文的元素部分中,我们将了解如何找出给定列表中每对元素的两个连续元素之间的差异。列表仅包含数字作为其元素。
使用索引
使用元素的索引以及 for 循环,我们可以找到连续元素对之间的差异。
示例
listA = [12,14,78,24,24]
# 给定列表
print("给定列表: \n",listA)
# Using Index positions
res = [listA[i + 1] - listA[i] for i in range(len(listA) - 1)]
# 打印结果
print ("元素连续差异列表:\n" ,res)
输出
运行上述代码得到以下结果 −
给定列表: [12, 14, 78, 24, 24] 元素连续差异列表: [2, 64, -54, 0]
使用切片
切片是另一种技术,我们从列表中切出连续的对,然后应用 zip 函数来获取结果。
示例
listA = [12,14,78,24,24]
# 给定列表
print("给定列表: \n",listA)
# 使用列表切片
res = [x - y for y, x in zip(listA[: -1], listA[1 :])]
# 打印结果
print ("元素连续差异列表 :\n" ,res)
输出
运行上述代码得到以下结果 −
输入列表: [12, 14, 78, 24, 24] 元素连续差异列表: [2, 64, -54, 0]
使用 sub
operators 模块中的 sub 方法也可以通过 map 函数使用。我们再次将切片技术应用于两个连续的元素对。
示例
import operator
listA = [12,14,78,24,24]
# 给定列表
print("给定列表: \n",listA)
# Using operator.sub
res = list(map(operator.sub, listA[1:], listA[:-1]))
# 打印结果
print ("List with successive difference in elements : \n" ,res)
输出
运行上述代码得到以下结果 −
给定列表: [12, 14, 78, 24, 24] List with successive difference in elements : [2, 64, -54, 0]
相关文章
有用资源
python 参考教程 - 该教程包含有关 python 的更多信息:https://www.cainiaomax.com/python/

