Python中的元组除法
有时,在处理记录时,我们可能会遇到需要跨元组执行数学除法运算的问题。在白天编程中可能会出现此问题。让我们讨论可以执行此任务的某些方式。
方法 #1:使用zip()
+ 生成器表达式
上述功能的组合可用于执行此任务。在此,我们使用生成器表达式执行除法任务,每个元组的映射索引由 zip() 完成。
# Python3 code to demonstrate working of
# Tuple division
# using zip() + generator expression
# initialize tuples
test_tup1 = (10, 4, 6, 9)
test_tup2 = (5, 2, 3, 3)
# printing original tuples
print("The original tuple 1 : " + str(test_tup1))
print("The original tuple 2 : " + str(test_tup2))
# Tuple division
# using zip() + generator expression
res = tuple(ele1 // ele2 for ele1, ele2 in zip(test_tup1, test_tup2))
# printing result
print("The divided tuple : " + str(res))
输出 :
The original tuple 1 : (10, 4, 6, 9)
The original tuple 2 : (5, 2, 3, 3)
The divided tuple : (2, 2, 2, 3)
方法 #2:使用map()
+ floordiv
上述功能的组合也可以执行此任务。在此,我们使用 floordiv 执行扩展除法逻辑的任务,映射由map()
完成。
# Python3 code to demonstrate working of
# Tuple division
# using map() + floordiv
from operator import floordiv
# initialize tuples
test_tup1 = (10, 4, 6, 9)
test_tup2 = (5, 2, 3, 3)
# printing original tuples
print("The original tuple 1 : " + str(test_tup1))
print("The original tuple 2 : " + str(test_tup2))
# Tuple division
# using map() + floordiv
res = tuple(map(floordiv, test_tup1, test_tup2))
# printing result
print("The divided tuple : " + str(res))
输出 :
The original tuple 1 : (10, 4, 6, 9)
The original tuple 2 : (5, 2, 3, 3)
The divided tuple : (2, 2, 2, 3)