📜  Python – 字典键的产品在列表中

📅  最后修改于: 2022-05-13 01:54:45.479000             🧑  作者: Mango

Python – 字典键的产品在列表中

使用Python字典可以进行许多操作,例如分组和转换。但有时,我们也会遇到需要对字典列表中键的值进行乘积的问题。此任务在日常编程中很常见。让我们讨论可以执行此任务的某些方式。

方法 #1:使用循环 + 列表推导
这是一种单行方法,用于执行获取特定键的乘积的任务,同时使用列表理解迭代到字典列表中的相似键。

# Python3 code to demonstrate working of
# Dictionary Key's Product in list
# Using loop + list comprehension
  
def prod(val) :     
    res = 1         
    for ele in val:         
        res *= ele         
    return res
  
# Initialize list
test_list = [{'gfg' : 1, 'is' : 2, 'best' : 3}, {'gfg' : 7, 'is' : 3, 'best' : 5}, {'gfg' : 9, 'is' : 8, 'best' : 6}] 
  
# printing original list
print("The original list is : " + str(test_list))
  
# Dictionary Key's Product in list
# Using loop + list comprehension
res = prod(sub['gfg'] for sub in test_list)
  
# printing result
print("The product of particular key is : " + str(res))
输出 :
The original list is : [{'is': 2, 'best': 3, 'gfg': 1}, {'is': 3, 'best': 5, 'gfg': 7}, {'is': 8, 'best': 6, 'gfg': 9}]
The product of particular key is : 63

方法 #2:使用循环 + itemgetter() + map()
这些功能的组合也可用于执行此任务。在此,主要区别在于理解任务由 map() 完成,而密钥访问任务由 itemgetter() 完成。

# Python3 code to demonstrate working of
# Dictionary Key's Product in list
# Using loop + itemgetter() + map()
import operator
  
def prod(val) :     
    res = 1         
    for ele in val:         
        res *= ele         
    return res
  
# Initialize list
test_list = [{'gfg' : 1, 'is' : 2, 'best' : 3}, {'gfg' : 7, 'is' : 3, 'best' : 5}, {'gfg' : 9, 'is' : 8, 'best' : 6}] 
  
# printing original list
print("The original list is : " + str(test_list))
  
# Dictionary Key's Product in list
# Using loop + itemgetter() + map()
res = prod(map(operator.itemgetter('gfg'), test_list))
  
# printing result
print("The product of particular key is : " + str(res))
输出 :
The original list is : [{'is': 2, 'best': 3, 'gfg': 1}, {'is': 3, 'best': 5, 'gfg': 7}, {'is': 8, 'best': 6, 'gfg': 9}]
The product of particular key is : 63