Python|添加元组
有时,在处理记录时,我们可能会遇到一个常见问题,即将一个元组的内容与另一个元组的相应索引相加。这几乎适用于我们处理元组记录的所有领域。让我们讨论可以执行此任务的某些方式。
方法 #1:使用map()
+ lambda
结合以上功能可以为我们解决问题。在此,我们使用 lambda 函数计算总和,并使用map()
将逻辑扩展到键。
# Python3 code to demonstrate working of
# Addition of tuples
# using map() + lambda
# 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))
# Addition of tuples
# using map() + lambda
res = tuple(map(lambda i, j: i + j, test_tup1, test_tup2))
# printing result
print("Resultant tuple after addition : " + str(res))
输出 :
The original tuple 1 : (10, 4, 5)
The original tuple 2 : (2, 5, 18)
Resultant tuple after addition : (12, 9, 23)
方法 #2:使用map() + zip() + sum()
上述功能的组合也可用于实现这一特定任务。在此,我们添加了内置sum()
来执行求和并使用zip()
压缩类似的索引,并使用map()
将逻辑扩展到两个元组。
# Python3 code to demonstrate working of
# Addition of tuples
# using map() + zip() + sum()
# 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))
# Addition of tuples
# using map() + zip() + sum()
res = tuple(map(sum, zip(test_tup1, test_tup2)))
# printing result
print("Resultant tuple after addition : " + str(res))
输出 :
The original tuple 1 : (10, 4, 5)
The original tuple 2 : (2, 5, 18)
Resultant tuple after addition : (12, 9, 23)