Python - 字典值列表长度产品
给定一个包含值作为列表的字典,计算每个列表的长度,并找到所有长度的乘积。
Input : test_dict = {‘Gfg’ : [6, 5, 9, 3], ‘is’ : [1, 3, 4], ‘best’ :[9, 16]}
Output : 24
Explanation : 4 * 3 * 2 = 24. Length of lists are 4, 3, and 2.
Input : test_dict = {‘Gfg’ : [6, 5, 3], ‘is’ : [1, 3, 4], ‘best’ :[9, 16]}
Output : 18
Explanation : 3 * 3 * 2 = 18. Length of lists are 3, 3, and 2.
方法 #1:使用循环 + len()
这是可以执行此任务的方式之一。在此,我们迭代所有值并使用 len() 来获取所有值列表的长度,然后我们执行整个数据的乘法。
Python3
# Python3 code to demonstrate working of
# Dictionary value lists lengths product
# Using loop + len()
# initializing dictionary
test_dict = {'Gfg' : [6, 5, 9, 3, 10],
'is' : [1, 3, 4],
'best' :[9, 16]}
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
# using loop to iterate through all keys
res = 1
for key in test_dict:
# len() used to get length of each value list
res = res * len(test_dict[key])
# printing result
print("The computed product : " + str(res))
Python3
# Python3 code to demonstrate working of
# Dictionary value lists lengths product
# Using map() + lambda + reduce()
from functools import reduce
# initializing dictionary
test_dict = {'Gfg' : [6, 5, 9, 3, 10],
'is' : [1, 3, 4],
'best' :[9, 16]}
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
# values() used to get all lists of keys
res = reduce(lambda sub1, sub2: sub1 * sub2, map(len, test_dict.values()))
# printing result
print("The computed product : " + str(res))
输出
The original dictionary is : {'Gfg': [6, 5, 9, 3, 10], 'is': [1, 3, 4], 'best': [9, 16]}
The computed product : 30
方法 #2:使用 map() + lambda + reduce()
上述功能的组合提供了一种解决此问题的方法。在此,我们使用 map() 来获取将 len() 扩展到每个列表的所有列表的长度,使用 lambda 来获取 product 并使用 reduce 来组合。
Python3
# Python3 code to demonstrate working of
# Dictionary value lists lengths product
# Using map() + lambda + reduce()
from functools import reduce
# initializing dictionary
test_dict = {'Gfg' : [6, 5, 9, 3, 10],
'is' : [1, 3, 4],
'best' :[9, 16]}
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
# values() used to get all lists of keys
res = reduce(lambda sub1, sub2: sub1 * sub2, map(len, test_dict.values()))
# printing result
print("The computed product : " + str(res))
输出
The original dictionary is : {'Gfg': [6, 5, 9, 3, 10], 'is': [1, 3, 4], 'best': [9, 16]}
The computed product : 30