Python|计算给定列表中相邻元素之间的差异
给定一个列表,任务是创建一个新列表,其中包含给定列表中相邻元素的差异。
方法 #1:使用zip()
# Python code to demonstrate
# to calculate difference
# between adjacent elements in list
# initialising _list
ini_list = [5, 4, 89, 12, 32, 45]
# printing iniial_list
print("intial_list", str(ini_list))
# Calculating difference list
diff_list = []
for x, y in zip(ini_list[0::], ini_list[1::]):
diff_list.append(y-x)
# printing difference list
print ("difference list: ", str(diff_list))
输出:
intial_list [5, 4, 89, 12, 32, 45]
difference list: [-1, 85, -77, 20, 13]
方法#2:使用朴素的方法
# Python code to demonstrate
# to calculate difference
# between adjacent elements in list
# initialising _list
ini_list = [5, 4, 89, 12, 32, 45]
# printing iniial_list
print("intial_list", str(ini_list))
# Calculating difference list
diff_list = []
for i in range(1, len(ini_list)):
diff_list.append(ini_list[i] - ini_list[i-1])
# printing difference list
print ("difference list: ", str(diff_list))
输出:
intial_list [5, 4, 89, 12, 32, 45]
difference list: [-1, 85, -77, 20, 13]
方法 #3:使用 numpy
# Python code to demonstrate
# to calculate difference
# between adjacent elements in list
import numpy as np
# initialising _list
ini_list = np.array([5, 4, 89, 12, 32, 45])
# printing iniial_list
print("intial_list", str(ini_list))
# Calculating difference list
diff_list = np.diff(ini_list)
# printing difference list
print ("difference list: ", str(diff_list))
输出:
intial_list [ 5 4 89 12 32 45]
difference list: [ -1 85 -77 20 13]