Python|列表值字典中的元素出现
有时我们可以有一项任务,我们需要计算列表或中奖号码中测试元素的出现次数,与以列表为值的关联键的数字。这可以在游戏或其他实用程序中应用。让我们讨论一些可以做到这一点的方法。
方法 #1:使用字典理解 + sum()
可以使用上述两个实用程序的组合来执行此任务,其中我们使用字典理解来绑定逻辑,并且 sum函数可用于执行从测试列表中找到的匹配项的求和。
# Python3 code to demonstrate
# Element Occurrence in dictionary value list
# using list comprehension + sum()
# initializing dictionary
test_dict = { "Akshat" : [1, 4, 5, 3],
"Nikhil" : [4, 6],
"Akash" : [5, 2, 1] }
# initializing test list
test_list = [2, 1]
# printing original dict
print("The original dictionary : " + str(test_dict))
# printing original list
print("The original list : " + str(test_list))
# using list comprehension + sum()
# Element Occurrence in dictionary value list
res = {idx : sum(1 for i in j if i in test_list)
for idx, j in test_dict.items()}
# print result
print("The summation of element occurrence : " + str(res))
输出 :
The original dictionary : {'Nikhil': [4, 6], 'Akshat': [1, 4, 5, 3], 'Akash': [5, 2, 1]}
The original list : [2, 1]
The summation of element occurrence : {'Nikhil': 0, 'Akshat': 1, 'Akash': 2}
方法 #2:使用collections.Counter()
Python提供了一个内置函数,该函数执行提取频率并使用它并调节测试列表中存在的任务,我们可以使用此函数解决上述问题。
# Python3 code to demonstrate
# Element Occurrence in dictionary value list
# using collections.Counter()
from collections import Counter
# initializing dictionary
test_dict = { "Akshat" : [1, 4, 5, 3],
"Nikhil" : [4, 6],
"Akash" : [5, 2, 1] }
# initializing test list
test_list = [2, 1]
# printing original dict
print("The original dictionary : " + str(test_dict))
# printing original list
print("The original list : " + str(test_list))
# using collections.Counter()
# Element Occurrence in dictionary value list
# omits the 0 occurrence word key
res = dict(Counter(j for j in test_dict
for i in test_list if i in test_dict[j]))
# print result
print("The summation of element occurrence : " + str(res))
输出 :
The original dictionary : {'Nikhil': [4, 6], 'Akshat': [1, 4, 5, 3], 'Akash': [5, 2, 1]}
The original list : [2, 1]
The summation of element occurrence : {'Akshat': 1, 'Akash': 2}