Python - 键的值频率
有时,在使用Python字典列表时,可能会遇到一个问题,即我们需要查找字典列表中特定键中所有值出现的频率。这可以跨许多领域应用,包括 Web 开发。让我们讨论可以执行此任务的某些方式。
Input : test_list = [{‘gfg’: [1]}, {‘good’: [5, 78, 10], ‘gfg’: [5, 6, 7, 8]}]
Output : {8: 1, 1: 1, 5: 1, 6: 1, 7: 1}
Input : test_list = [{‘gfg’: [1, 5, 6, 7]}]
Output : {1: 1, 5: 1, 6: 1, 7: 1}
方法 #1:使用Counter()
+ 列表推导
上述功能的组合用于解决这个问题。在此,我们使用 Counter() 执行查找频率的任务,并使用列表理解完成计算。
# Python3 code to demonstrate working of
# Values frequencies of key
# Using Counter() + list comprehension
from collections import Counter
# initializing list
test_list = [{'gfg' : [1, 5, 6, 7], 'is' : [9, 6, 2, 10]},
{'gfg' : [5, 6, 7, 8], 'good' : [5, 7, 10]},
{'gfg' : [7, 5], 'best' : [5, 7]}]
# printing original list
print("The original list is : " + str(test_list))
# frequency key
freq_key = "gfg"
# Values frequencies of key
# Using Counter() + list comprehension
res = Counter([idx for val in test_list for idx in val[freq_key]])
# printing result
print("The frequency dictionary : " + str(dict(res)))
The original list is : [{‘gfg’: [1, 5, 6, 7], ‘is’: [9, 6, 2, 10]}, {‘gfg’: [5, 6, 7, 8], ‘good’: [5, 7, 10]}, {‘gfg’: [7, 5], ‘best’: [5, 7]}]
The frequency dictionary : {8: 1, 1: 1, 5: 3, 6: 2, 7: 3}
方法 #2:使用chain.from_iterables() + Counter()
上述方法的组合可以用来解决这个问题。在此,我们使用chain.from_iterables() 执行迭代和绑定任务。
# Python3 code to demonstrate working of
# Values frequencies of key
# Using chain.from_iterables() + Counter()
from collections import Counter
import itertools
# initializing list
test_list = [{'gfg' : [1, 5, 6, 7], 'is' : [9, 6, 2, 10]},
{'gfg' : [5, 6, 7, 8], 'good' : [5, 7, 10]},
{'gfg' : [7, 5], 'best' : [5, 7]}]
# printing original list
print("The original list is : " + str(test_list))
# frequency key
freq_key = "gfg"
# Values frequencies of key
# Using chain.from_iterables() + Counter()
res = Counter(itertools.chain.from_iterable([sub[freq_key] for sub in test_list]))
# printing result
print("The frequency dictionary : " + str(dict(res)))
The original list is : [{‘gfg’: [1, 5, 6, 7], ‘is’: [9, 6, 2, 10]}, {‘gfg’: [5, 6, 7, 8], ‘good’: [5, 7, 10]}, {‘gfg’: [7, 5], ‘best’: [5, 7]}]
The frequency dictionary : {8: 1, 1: 1, 5: 3, 6: 2, 7: 3}