Python - 元组列表中连续第 K 列的差异
有时,在使用Python列表时,我们可能有一项任务需要使用元组列表并获得它的第 K 个索引的绝对差异。这个问题在处理数据信息时在 web 开发领域有应用。让我们讨论可以执行此任务的某些方式。
例子:
Input : test_list = [(5, 4, 2), (1, 3, 4), (5, 7, 8), (7, 4, 3)], K = 0
Output : [4, 4, 2]
Explanation : 5 – 1 = 4, hence 4.
Input : test_list = [(5, 4, 2), (1, 3, 4), (5, 7, 8), (7, 4, 3)], K = 2
Output : [2, 4, 5]
Explanation : 8 – 3 = 5, hence 5.
方法#1:使用循环
在这里,对于每个元组,我们减去并找到第 K 列元组与列表中连续元组的绝对差。
Python3
# Python3 code to demonstrate working of
# Consecutive Kth column Difference in Tuple List
# Using loop
# initializing list
test_list = [(5, 4, 2), (1, 3, 4), (5, 7, 8), (7, 4, 3)]
# printing original list
print("The original list is : " + str(test_list))
# initializing K
K = 1
res = []
for idx in range(0, len(test_list) - 1):
# getting difference using abs()
res.append(abs(test_list[idx][K] - test_list[idx + 1][K]))
# printing result
print("Resultant tuple list : " + str(res))
Python3
# Python3 code to demonstrate working of
# Consecutive Kth column Difference in Tuple List
# Using zip() + list comprehension
# initializing list
test_list = [(5, 4, 2), (1, 3, 4), (5, 7, 8), (7, 4, 3)]
# printing original list
print("The original list is : " + str(test_list))
# initializing K
K = 1
# zip used to pair each tuple with subsequent tuple
res = [abs(x[K] - y[K]) for x, y in zip(test_list, test_list[1:])]
# printing result
print("Resultant tuple list : " + str(res))
输出:
The original list is : [(5, 4, 2), (1, 3, 4), (5, 7, 8), (7, 4, 3)]
Resultant tuple list : [1, 4, 3]
方法 #2:使用 zip() + 列表理解
在这里,我们使用列表推导对列表中的所有元素进行迭代,并使用 zip() 比较配对的元素。
蟒蛇3
# Python3 code to demonstrate working of
# Consecutive Kth column Difference in Tuple List
# Using zip() + list comprehension
# initializing list
test_list = [(5, 4, 2), (1, 3, 4), (5, 7, 8), (7, 4, 3)]
# printing original list
print("The original list is : " + str(test_list))
# initializing K
K = 1
# zip used to pair each tuple with subsequent tuple
res = [abs(x[K] - y[K]) for x, y in zip(test_list, test_list[1:])]
# printing result
print("Resultant tuple list : " + str(res))
输出:
The original list is : [(5, 4, 2), (1, 3, 4), (5, 7, 8), (7, 4, 3)]
Resultant tuple list : [1, 4, 3]