📜  Python – 获取元组对中的最小差异

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

Python – 获取元组对中的最小差异

有时,在处理数据时,我们可能会遇到一个问题,即我们需要找到列表中可用对之间的最小差异。这可以应用于数学领域的许多问题。让我们讨论可以执行此任务的某些方式。
方法 #1:使用 min() + 列表推导
此功能的组合可用于执行此任务。在此,我们计算所有对的绝对差,然后使用 min() 返回它的最小值。

Python3
# Python3 code to demonstrate working of
# Tuple minimum difference in pair
# Using list comprehension + min()
 
# initialize list
test_list = [(3, 5), (1, 7), (10, 3), (1, 2)]
 
# printing original list
print("The original list : " + str(test_list))
 
# Tuple minimum difference in pair
# Using list comprehension + min()
temp = [abs(b - a) for a, b in test_list]
res = min(temp)
 
# printing result
print("Minimum difference among pairs : " + str(res))


Python3
# Python3 code to demonstrate working of
# Tuple minimum difference in pair
# Using lambda + min()
 
# initialize list
test_list = [(3, 5), (1, 7), (10, 3), (1, 2)]
 
# printing original list
print("The original list : " + str(test_list))
 
# Tuple minimum difference in pair
# Using lambda + min()
res = min(test_list, key = lambda sub: abs(sub[1] - sub[0]))
 
# printing result
print("Minimum difference among pairs : " + str(res))


输出 :
The original list : [(3, 5), (1, 7), (10, 3), (1, 2)]
Minimum difference among pairs : 1


方法 #2:使用 min() + lambda
这与上述方法类似。在此,列表推导执行的任务是使用 lambda函数解决的,提供差异计算逻辑。返回最小值。差异对。

Python3

# Python3 code to demonstrate working of
# Tuple minimum difference in pair
# Using lambda + min()
 
# initialize list
test_list = [(3, 5), (1, 7), (10, 3), (1, 2)]
 
# printing original list
print("The original list : " + str(test_list))
 
# Tuple minimum difference in pair
# Using lambda + min()
res = min(test_list, key = lambda sub: abs(sub[1] - sub[0]))
 
# printing result
print("Minimum difference among pairs : " + str(res))
输出 :
The original list : [(3, 5), (1, 7), (10, 3), (1, 2)]
Minimum difference among pairs : (1, 2)