Python – 字典中的元组值乘积
有时,在处理数据时,我们可能会遇到一个问题,即我们需要找到作为字典值接收的元组元素的乘积。我们可能有一个问题来获得索引明智的产品。让我们讨论一些可以解决这个特定问题的方法。
方法#1:使用tuple() + loop + zip() + values()
上述方法的组合可用于执行此特定任务。在此,我们只是
使用 zip() 将 values() 提取的 equi 索引值压缩在一起。然后使用相应的函数查找产品。最后,结果作为索引乘积作为元组返回。
# Python3 code to demonstrate working of
# Dictionary Tuple Values Product
# Using tuple() + loop + zip() + values()
# getting Product
def prod(val) :
res = 1
for ele in val:
res *= ele
return res
# Initializing dictionary
test_dict = {'gfg' : (5, 6, 1), 'is' : (8, 3, 2), 'best' : (1, 4, 9)}
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
# Dictionary Tuple Values Product
# Using tuple() + loop + zip() + values()
res = tuple(prod(x) for x in zip(*test_dict.values()))
# printing result
print("The product from each index is : " + str(res))
输出 :
The original dictionary is : {'gfg': (5, 6, 1), 'is': (8, 3, 2), 'best': (1, 4, 9)}
The product from each index is : (40, 72, 18)
方法 #2:使用tuple() + map() + values()
这是可以执行此任务的另一种方式。不同之处在于我们使用 map() 而不是循环。
# Python3 code to demonstrate working of
# Dictionary Tuple Values Product
# Using tuple() + map() + values()
# getting Product
def prod(val) :
res = 1
for ele in val:
res *= ele
return res
# Initializing dictionary
test_dict = {'gfg' : (5, 6, 1), 'is' : (8, 3, 2), 'best' : (1, 4, 9)}
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
# Dictionary Tuple Values Product
# Using tuple() + map() + values()
temp = []
for sub in test_dict.values():
temp.append(list(sub))
res = tuple(map(prod, temp))
# printing result
print("The product from each index is : " + str(res))
输出 :
The original dictionary is : {'gfg': (5, 6, 1), 'is': (8, 3, 2), 'best': (1, 4, 9)}
The product from each index is : (40, 72, 18)