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