Python – 将 K 添加到列元组列表中的最小元素
有时,在处理元组记录时,我们可能会遇到一个问题,我们需要执行将某个元素添加到元组列表每一列的最大/最小元素的任务。这种问题可以在Web开发领域有应用。让我们讨论一下可以执行此任务的某种方式。
Input : test_list = [(4, 5), (3, 2), (2, 2), (4, 6), (3, 2), (4, 5)], K = 2
Output : [(4, 5), (3, 4), (4, 4), (4, 6), (3, 4), (4, 5)]
Input : test_list = [(4, 5), (3, 2), (2, 2), (4, 6), (3, 2), (4, 5)], K = 3
Output : [(4, 5), (3, 5), (5, 5), (4, 6), (3, 5), (4, 5)]
方法:使用min()
+ 循环
上述功能的组合可以用来解决这个问题。在此,我们执行使用 min() 为每列提取 min 的任务,并使用循环中编译的逻辑添加 K。
# Python3 code to demonstrate working of
# Add K to Minimum element in Column Tuple List
# Using min() + loop
# initializing lists
test_list = [(4, 5), (3, 2), (2, 2), (4, 6), (3, 2), (4, 5)]
# printing original list
print("The original list is : " + str(test_list))
# initializing K
K = 5
# Add K to Minimum element in Column Tuple List
# Using min() + loop
a_min = min(a for a, b in test_list)
b_min = min(b for a, b in test_list)
res = []
for a, b in test_list:
if a == a_min and b == b_min:
res.append((a + K, b + K))
elif a == a_min :
res.append((a + K, b))
elif b == b_min:
res.append((a, b + K))
else :
res.append((a, b))
# printing result
print("Tuple after modification : " + str(res))
输出 :
The original list is : [(4, 5), (3, 2), (2, 2), (4, 6), (3, 2), (4, 5)]
Tuple after modification : [(4, 5), (3, 7), (7, 7), (4, 6), (3, 7), (4, 5)]