Python – 元组列表中总和等于 K 的对
有时,在处理数据时,我们可能会遇到需要查找元组列表对的总和的问题。特别是等于 K 的总和。这类问题在 Web 开发和竞争性编程中可能很重要。让我们讨论可以执行此任务的某些方式。
方法#1:使用循环
这可以使用循环来解决。这是执行此任务的粗暴方式。在此,我们迭代列表以进行对求和并保留其总和为 K。
# Python3 code to demonstrate
# Pairs with Sum equal to K in tuple list
# using loop
# Initializing list
test_list = [(4, 5), (6, 7), (3, 6), (1, 2), (1, 8)]
# printing original list
print("The original list is : " + str(test_list))
# Initializing K
K = 9
# Pairs with Sum equal to K in tuple list
# using loop
res = []
for ele in test_list:
if ele[0] + ele[1] == K:
res.append(ele)
# printing result
print ("List after extracting pairs equal to K : " + str(res))
输出 :
The original list is : [(4, 5), (6, 7), (3, 6), (1, 2), (1, 8)]
List after extracting pairs equal to K : [(4, 5), (3, 6), (1, 8)]
方法#2:使用列表推导
这是可以执行此任务的另一种方式。在此,我们以与上述类似的方法提取元素,不同之处在于我们以简写形式执行此任务并且在一行中执行。
# Python3 code to demonstrate
# Pairs with Sum equal to K in tuple list
# using list comprehension
# Initializing list
test_list = [(4, 5), (6, 7), (3, 6), (1, 2), (1, 8)]
# printing original list
print("The original list is : " + str(test_list))
# Initializing K
K = 9
# Pairs with Sum equal to K in tuple list
# using list comprehension
res = [(ele[0], ele[1]) for ele in test_list if ele[0] + ele[1] == K]
# printing result
print ("List after extracting pairs equal to K : " + str(res))
输出 :
The original list is : [(4, 5), (6, 7), (3, 6), (1, 2), (1, 8)]
List after extracting pairs equal to K : [(4, 5), (3, 6), (1, 8)]