Python – 元组中最接近第 K 个索引元素的对
有时,在处理Python记录时,我们可能会遇到一个问题,即我们需要找到最接近某个元组的元组,并在特定索引上进行查询。这类问题可以应用于数据领域,例如 Web 开发。让我们讨论可以执行此任务的某些方式。
Input :
test_list = [(3, 4), (78, 76), (2, 3), (9, 8), (19, 23)]
tup = (17, 23)
K = 2
Output : (19, 23)
Input :
test_list = [(3, 4, 9), (5, 6, 7)]
tup = (1, 2, 5)
K = 3
Output : (5, 6, 7)
方法 #1:使用enumerate()
+ 循环
上述功能的组合提供了解决这个问题的蛮力方法。在这种情况下,我们使用 enumerate() 来监控 index 和 abs() 来保持在循环中检查每个元素的最小差异更新。
# Python3 code to demonstrate working of
# Closest Pair to Kth index element in Tuple
# Using enumerate() + loop
# initializing list
test_list = [(3, 4), (78, 76), (2, 3), (9, 8), (19, 23)]
# printing original list
print("The original list is : " + str(test_list))
# initializing tuple
tup = (17, 23)
# initializing K
K = 1
# Closest Pair to Kth index element in Tuple
# Using enumerate() + loop
min_dif, res = 999999999, None
for idx, val in enumerate(test_list):
dif = abs(tup[K - 1] - val[K - 1])
if dif < min_dif:
min_dif, res = dif, idx
# printing result
print("The nearest tuple to Kth index element is : " + str(test_list[res]))
输出 :
The original list is : [(3, 4), (78, 76), (2, 3), (9, 8), (19, 23)]
The nearest tuple to Kth index element is : (19, 23)
方法 #2:使用min()
+ lambda
上述功能的组合为解决这个问题提供了简写。在此,我们使用 min() 来找到最小元素差异,并使用 lambda函数来执行迭代和计算。
# Python3 code to demonstrate working of
# Closest Pair to Kth index element in Tuple
# Using min() + lambda
# initializing list
test_list = [(3, 4), (78, 76), (2, 3), (9, 8), (19, 23)]
# printing original list
print("The original list is : " + str(test_list))
# initializing tuple
tup = (17, 23)
# initializing K
K = 1
# Closest Pair to Kth index element in Tuple
# Using min() + lambda
res = min(range(len(test_list)), key = lambda sub: abs(test_list[sub][K - 1] - tup[K - 1]))
# printing result
print("The nearest tuple to Kth index element is : " + str(test_list[res]))
输出 :
The original list is : [(3, 4), (78, 76), (2, 3), (9, 8), (19, 23)]
The nearest tuple to Kth index element is : (19, 23)