Python|累积嵌套元组列产品
有时,在处理记录时,我们可能会遇到需要对元组元素执行索引乘法的问题。这可能会变得复杂,因为元组元素是元组,而内部元素又是元组。让我们讨论一些可以解决这个问题的方法。
方法 #1:使用 zip() + 嵌套生成器表达式
上述功能的组合可用于执行任务。在此,我们使用 zip() 跨元组组合元素。迭代和产品逻辑由生成器表达式提供。
Python3
# Python3 code to demonstrate working of
# Cumulative Nested Tuple Column Product
# using zip() + nested generator expression
# 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))
# Cumulative Nested Tuple Column Product
# using zip() + nested generator expression
res = tuple(tuple(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 product : " + str(res))
Python3
# Python3 code to demonstrate working of
# Cumulative Nested Tuple Column Product
# using isinstance() + zip() + loop + list comprehension
# function to perform task
def tup_prod(tup1, tup2):
if isinstance(tup1, (list, tuple)) and isinstance(tup2, (list, tuple)):
return tuple(tup_prod(x, y) for x, y in zip(tup1, tup2))
return 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))
# Cumulative Nested Tuple Column Product
# using isinstance() + zip() + loop + list comprehension
res = tuple(tup_prod(x, y) for x, y in zip(test_tup1, test_tup2))
# printing result
print("The resultant tuple after product : " + 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 product : ((6, 21), (12, 45), (2, 9), (7, 30))
方法 #2:使用 isinstance() + zip() + 循环 + 列表理解
上述功能的组合可用于执行此特定任务。在此,我们检查嵌套类型并执行递归。这种方法可以提供超过 1 级嵌套的灵活性。
Python3
# Python3 code to demonstrate working of
# Cumulative Nested Tuple Column Product
# using isinstance() + zip() + loop + list comprehension
# function to perform task
def tup_prod(tup1, tup2):
if isinstance(tup1, (list, tuple)) and isinstance(tup2, (list, tuple)):
return tuple(tup_prod(x, y) for x, y in zip(tup1, tup2))
return 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))
# Cumulative Nested Tuple Column Product
# using isinstance() + zip() + loop + list comprehension
res = tuple(tup_prod(x, y) for x, y in zip(test_tup1, test_tup2))
# printing result
print("The resultant tuple after product : " + 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 product : ((6, 21), (12, 45), (2, 9), (7, 30))