Python – 最大化嵌套元组
有时,在处理记录时,我们可能会遇到需要对元组元素执行索引最大值的问题。这可能会变得复杂,因为元组元素是元组,而内部元素又是元组。让我们讨论一些可以解决这个问题的方法。
方法 #1:使用zip() + max()
+ 嵌套生成器表达式
上述功能的组合可用于执行任务。在此,我们使用 zip() 跨元组组合元素。迭代和最大化逻辑由生成器表达式提供。
# Python3 code to demonstrate working of
# Maximizing Nested Tuples
# using zip() + nested generator expression + max()
# initialize tuples
test_tup1 = ((1, 3), (4, 5), (2, 9), (1, 10))
test_tup2 = ((6, 7), (3, 9), (1, 1), (7, 3))
# printing original tuples
print("The original tuple 1 : " + str(test_tup1))
print("The original tuple 2 : " + str(test_tup2))
# Maximizing Nested Tuples
# using zip() + nested generator expression + max()
res = tuple(tuple(max(a, b) for a, b in zip(tup1, tup2))\
for tup1, tup2 in zip(test_tup1, test_tup2))
# printing result
print("The resultant tuple after maximization : " + str(res))
输出 :
The original tuple 1 : ((1, 3), (4, 5), (2, 9), (1, 10))
The original tuple 2 : ((6, 7), (3, 9), (1, 1), (7, 3))
The resultant tuple after maximization : ((6, 7), (4, 9), (2, 9), (7, 10))
方法 #2:使用isinstance() + zip() + max()
+ loop + 列表理解
上述功能的组合可用于执行此特定任务。在此,我们检查嵌套类型并执行递归。这种方法可以提供超过 1 级嵌套的灵活性。
# Python3 code to demonstrate working of
# Maximizing Nested Tuples
# using isinstance() + zip() + loop + list comprehension + max()
# function to perform task
def tup_max(tup1, tup2):
if isinstance(tup1, (list, tuple)) and isinstance(tup2, (list, tuple)):
return tuple(tup_max(x, y) for x, y in zip(tup1, tup2))
return max(tup1, tup2)
# initialize tuples
test_tup1 = ((1, 3), (4, 5), (2, 9), (1, 10))
test_tup2 = ((6, 7), (3, 9), (1, 1), (7, 3))
# printing original tuples
print("The original tuple 1 : " + str(test_tup1))
print("The original tuple 2 : " + str(test_tup2))
# Maximizing Nested Tuples
# using isinstance() + zip() + loop + list comprehension + max()
res = tuple(tup_max(x, y) for x, y in zip(test_tup1, test_tup2))
# printing result
print("The resultant tuple after maximization : " + str(res))
输出 :
The original tuple 1 : ((1, 3), (4, 5), (2, 9), (1, 10))
The original tuple 2 : ((6, 7), (3, 9), (1, 1), (7, 3))
The resultant tuple after maximization : ((6, 7), (4, 9), (2, 9), (7, 10))