📜  Python – 连续元组差异

📅  最后修改于: 2022-05-13 01:55:29.620000             🧑  作者: Mango

Python – 连续元组差异

给定元组列表,找到连续元组的索引绝对差。

方法#1:使用列表推导

这是可以执行此任务的一种方式。在此,我们使用列表理解策略对列表采用蛮力策略,以单行执行此任务。

Python3
# Python3 code to demonstrate working of 
# Consecutive Tuple difference
# Using list comprehension
  
# initializing lists
test_list = [(6, 3), (1, 4), (8, 5), (3, 5)]
  
# printing original list
print("The original list : " + str(test_list))
  
# using list comprehension to perform absolute difference
# using abs() for difference
res = [(abs(test_list[idx + 1][0] - test_list[idx][0]), abs(test_list[idx + 1][1] - test_list[idx][1])) 
      for idx in range(len(test_list) - 1)]
  
# printing result 
print("The extracted list : " + str(res))


Python3
# Python3 code to demonstrate working of 
# Consecutive Tuple difference
# Using tuple() + map() + sub
from operator import sub
  
# initializing lists
test_list = [(6, 3), (1, 4), (8, 5), (3, 5)]
  
# printing original list
print("The original list : " + str(test_list))
  
# using loop to iterate elements
# using sub and map() to perform the subtraction to whole elements
res = []
for idx in range(len(test_list) - 1):
    res.append(tuple(map(sub, test_list[idx + 1][0:], test_list[idx][0:])))
      
# printing result 
print("The extracted list : " + str(res))


输出
The original list : [(6, 3), (1, 4), (8, 5), (3, 5)]
The extracted list : [(5, 1), (7, 1), (5, 0)]

方法#2:使用 tuple() + map() + sub

上述功能的组合可以用来解决这个问题。在此,我们使用 sub 执行减法任务,并使用 map() 将逻辑扩展到整个列表元素。不输出绝对结果。

Python3

# Python3 code to demonstrate working of 
# Consecutive Tuple difference
# Using tuple() + map() + sub
from operator import sub
  
# initializing lists
test_list = [(6, 3), (1, 4), (8, 5), (3, 5)]
  
# printing original list
print("The original list : " + str(test_list))
  
# using loop to iterate elements
# using sub and map() to perform the subtraction to whole elements
res = []
for idx in range(len(test_list) - 1):
    res.append(tuple(map(sub, test_list[idx + 1][0:], test_list[idx][0:])))
      
# printing result 
print("The extracted list : " + str(res))
输出
The original list : [(6, 3), (1, 4), (8, 5), (3, 5)]
The extracted list : [(-5, 1), (7, 1), (-5, 0)]