📜  Python|元组之间的索引最大值

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

Python|元组之间的索引最大值

有时,在处理记录时,我们可能会遇到一个常见问题,即最大化一个元组的内容与另一个元组的相应索引。这几乎适用于我们处理元组记录的所有领域。让我们讨论可以执行此任务的某些方式。

方法 #1:使用map() + lambda + max()
结合以上功能可以为我们解决问题。在此,我们使用 lambda 函数和 max() 计算最大值,并使用 map() 将逻辑扩展到键。

# Python3 code to demonstrate working of
# Index Maximum among Tuples
# using map() + lambda + max()
  
# initialize tuples 
test_tup1 = (10, 4, 5)
test_tup2 = (2, 5, 18)
  
# printing original tuples 
print("The original tuple 1 : " + str(test_tup1))
print("The original tuple 2 : " + str(test_tup2))
  
# Index Maximum among Tuples
# using map() + lambda + max()
res = tuple(map(lambda i, j: max(i, j), test_tup1, test_tup2))
  
# printing result
print("Resultant tuple after maximization : " + str(res))
输出 :
The original tuple 1 : (10, 4, 5)
The original tuple 2 : (2, 5, 18)
Resultant tuple after maximization : (10, 5, 18)

方法 #2:使用map() + zip() + max()
上述功能的组合也可用于实现这一特定任务。在此,我们添加了内置的 max() 来执行最大化并使用 zip() 压缩类似的索引,并使用 map() 将逻辑扩展到两个元组。

# Python3 code to demonstrate working of
# Index Maximum among Tuples
# using map() + zip() + max()
  
# initialize tuples 
test_tup1 = (10, 4, 5)
test_tup2 = (2, 5, 18)
  
# printing original tuples 
print("The original tuple 1 : " + str(test_tup1))
print("The original tuple 2 : " + str(test_tup2))
  
# Index Maximum among Tuples
# using map() + zip() + max()
res = tuple(map(max, zip(test_tup1, test_tup2)))
  
# printing result
print("Resultant tuple after maximization : " + str(res))
输出 :
The original tuple 1 : (10, 4, 5)
The original tuple 2 : (2, 5, 18)
Resultant tuple after maximization : (10, 5, 18)