Python – 字典值列表的累积产品
有时,在使用Python字典时,我们可以将其值作为列表。在这种情况下,我们可能会遇到一个问题,即我们只需要这些列表中元素的乘积作为一个整体。这可能是数据科学中的一个问题,我们需要在观察中获取总记录。让我们讨论一下可以执行此任务的某些方式
方法 #1:使用循环 + 列表推导
此任务可以使用显式产品函数来执行,该函数可用于获取产品,并且内部列表理解可以提供一种机制来将此逻辑迭代到字典的所有键。
Python3
# Python3 code to demonstrate working of
# Cumulative product of dictionary value lists
# using loop + list comprehension
def prod(val) :
res = 1
for ele in val:
res *= ele
return res
# initialize dictionary
test_dict = {'gfg' : [5, 6, 7], 'is' : [10, 11], 'best' : [19, 31, 22]}
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
# Cumulative product of dictionary value lists
# using loop + list comprehension
res = sum(prod(sub) for sub in test_dict.values())
# printing result
print("Product of dictionary list values are : " + str(res))
Python3
# Python3 code to demonstrate working of
# Cumulative product of dictionary value lists
# using loop + map()
def prod(val) :
res = 1
for ele in val:
res *= ele
return res
# initialize dictionary
test_dict = {'gfg' : [5, 6, 7], 'is' : [10, 11], 'best' : [19, 31, 22]}
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
# Cumulative product of dictionary value lists
# using loop + map()
res = sum(map(prod, test_dict.values()))
# printing result
print("Product of dictionary list values are : " + str(res))
输出 :
The original dictionary is : {'best': [19, 31, 22], 'gfg': [5, 6, 7], 'is': [10, 11]}
Product of dictionary list values are : 13278
方法 #2:使用循环 + map()
也可以使用 map函数代替列表推导来执行此任务,以扩展查找产品的逻辑,其余所有功能与上述方法相同。
Python3
# Python3 code to demonstrate working of
# Cumulative product of dictionary value lists
# using loop + map()
def prod(val) :
res = 1
for ele in val:
res *= ele
return res
# initialize dictionary
test_dict = {'gfg' : [5, 6, 7], 'is' : [10, 11], 'best' : [19, 31, 22]}
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
# Cumulative product of dictionary value lists
# using loop + map()
res = sum(map(prod, test_dict.values()))
# printing result
print("Product of dictionary list values are : " + str(res))
输出 :
The original dictionary is : {'best': [19, 31, 22], 'gfg': [5, 6, 7], 'is': [10, 11]}
Product of dictionary list values are : 13278