#!/usr/bin/env python3
# -*- coding: UTF-8 -*-
from random import randint
data = [randint(0, 20) for _ in range(30)]
'''第一种方法'''
# 先将列表转化为字典,重复的键保留一个,初始化值为0
d = {}
for i in data:
d[i] = 0
# 也可以使用字典 fromkeys() 函数
# 以序列 seq 中元素做字典的键,value 为字典所有键对应的初始值
# d = dict.fromkeys(data, 0)
# 初始化完成后再对列表进行迭代,当出现一个重复的键对其加1
for i in data:
d[i] += 1
print(d)
'''第二种方法'''
# 使用字典 get() 函数返回指定键的值,如果值不在字典中返回默认值
d2 = {}
for i in data:
d2[i] = d2.get(i, 0) + 1
print(d2)
collections.Counter
统计元素出现的频率from collections import Counter
d3 = Counter(data)
print(dict(d3))
# most_common(3) 是取出频率最高的3个元素
print(d3.most_common(3))
运行结果:
Geek-Mac:Downloads zhangyi$ python3 Nice.py
{5: 3, 19: 2, 20: 1, 15: 2, 10: 4, 3: 2, 2: 3, 8: 1, 1: 4, 4: 2, 7: 1, 18: 1, 16: 1, 9: 1, 6: 1, 0: 1}
{5: 3, 19: 2, 20: 1, 15: 2, 10: 4, 3: 2, 2: 3, 8: 1, 1: 4, 4: 2, 7: 1, 18: 1, 16: 1, 9: 1, 6: 1, 0: 1}
{5: 3, 19: 2, 20: 1, 15: 2, 10: 4, 3: 2, 2: 3, 8: 1, 1: 4, 4: 2, 7: 1, 18: 1, 16: 1, 9: 1, 6: 1, 0: 1}
[(10, 4), (1, 4), (5, 3)]