📜  计算字典频率的Python程序

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

计算字典频率的Python程序

给定一个字典列表,这里的任务是编写一个Python程序来提取每个字典的字典频率。

方法 1:使用index()循环

在这种情况下,迭代每个字典,并使用 index() 获取字典的索引与其增加的频率映射,并在重复字典的情况下增加计数器。

例子:

Python3
# initializing list
test_list = [{'gfg': 1, 'is': 4, 'best': 9},
             {'gfg': 6, 'is': 3, 'best': 8},
             {'gfg': 1, 'is': 4, 'best': 9},
             {'gfg': 1, 'is': 1, 'best': 9},
             {'gfg': 6, 'is': 3, 'best': 8}]
  
# printing original list
print("The original list is : " + str(test_list))
  
res = []
for sub in test_list:
  
    flag = 0
    for ele in res:
  
        # checking for presence and incrementing frequency
        if sub == ele[0]:
            res[res.index(ele)] = (sub, ele[1] + 1)
            flag = 1
  
    if not flag:
        res.append((sub, 1))
  
# printing result
print("Dictionaries frequencies : " + str(res))


Python3
from collections import Counter
  
# initializing list
test_list = [{'gfg': 1, 'is': 4, 'best': 9},
             {'gfg': 6, 'is': 3, 'best': 8},
             {'gfg': 1, 'is': 4, 'best': 9},
             {'gfg': 1, 'is': 1, 'best': 9},
             {'gfg': 6, 'is': 3, 'best': 8}]
  
# printing original list
print("The original list is : " + str(test_list))
  
# getting frequencies
temp = Counter(tuple(sorted(sub.items())) for sub in test_list)
  
# converting back to Dictionaries
res = [(dict([tuple(ele) for ele in sub]), temp[sub]) for sub in temp]
  
# printing result
print("Dictionaries frequencies : " + str(res))


输出:

方法 2:使用Counter()sorted()

在这种情况下,字典元素被转换为元组对,然后使用 Counter 来获取每个元素的频率。在最后一步,每本词典都被重新转换成原来的形式。

例子:

蟒蛇3

from collections import Counter
  
# initializing list
test_list = [{'gfg': 1, 'is': 4, 'best': 9},
             {'gfg': 6, 'is': 3, 'best': 8},
             {'gfg': 1, 'is': 4, 'best': 9},
             {'gfg': 1, 'is': 1, 'best': 9},
             {'gfg': 6, 'is': 3, 'best': 8}]
  
# printing original list
print("The original list is : " + str(test_list))
  
# getting frequencies
temp = Counter(tuple(sorted(sub.items())) for sub in test_list)
  
# converting back to Dictionaries
res = [(dict([tuple(ele) for ele in sub]), temp[sub]) for sub in temp]
  
# printing result
print("Dictionaries frequencies : " + str(res))

输出: