python字典统计排序1_python实例:元组命名 频次统计 字典排序

1.为元组中元素命名

方法1.定义常量

NAME, AGE = 0, 1student= ('乔峰', 29, 'qf@jinyong.com')

name=student[NAME]

age= student[AGE]

方法2.使用 namedtuple

from collections importnamedtuple

Student= namedtuple('Student', ['name', 'age', 'email'])

stu= Student('乔峰', 29, 'qf@jinyong.com')

name=stu.name

age=stu.age

2. 统计数组元素频次

方法1. 生成字典统计

lis = [8, 9, 9, 9, 9, 2, 10, 0, 7, 6, 2, 5, 1, 5, 0, 10, 8, 4, 1, 1, 6, 5, 10, 7, 9, 3, 2, 5, 3, 10]

# 生成字典 键 = 数组元素,值 = 0

d= dict.fromkeys(lis, 0) #{8: 0, 9: 0, 2: 0, 10: 0, 0: 0, 7: 0, 6: 0, 5: 0, 1: 0, 4: 0, 3: 0}

# 遍历数组,统计频次

for x inlis:

d[x]+= 1

print(d) #{8: 2, 9: 5, 2: 3, 10: 4, 0: 2, 7: 2, 6: 2, 5: 4, 1: 3, 4: 1, 3: 2}

方法2. 使用Counter

from collections importCounter

lis= [8, 9, 9, 9, 9, 2, 10, 0, 7, 6, 2, 5, 1, 5, 0, 10, 8, 4, 1, 1, 6, 5, 10, 7, 9, 3, 2, 5, 3, 10]

ret=Counter(lis)print(ret) #{8: 2, 9: 5, 2: 3, 10: 4, 0: 2, 7: 2, 6: 2, 5: 4, 1: 3, 4: 1, 3: 2}

#出现频次最高的项

top = ret.most_common(3)

print(top) # [(9, 5), (10, 4), (5, 4)]

3.按字典值排序

方法1 使用元组

score = {'a': 72, 'b': 97, 'c': 81, 'x': 75, 'y': 84, 'z': 93}

# 根据字典的值,键,生成元组

score_tup=zip(score.values(), score.keys()) # 生成元组 (72, 'a'), (97, 'b'), (81, 'c'), (75, 'x'), (84, 'y'), (93, 'z')

# 排序

sorted_score=sorted(score_tup)print(sorted_score) # [(72, 'a'), (75, 'x'), (81, 'c'), (84, 'y'), (93, 'z'), (97, 'b')]

方法2 使用 sorted 的key

score = {'a': 72, 'b': 97, 'c': 81, 'x': 75, 'y': 84, 'z': 93}

# score.items = dict_items([('a', 72), ('b', 97), ('c', 81), ('x', 75), ('y', 84), ('z', 93)])

# 用 lambda 参数中 x 的第一项排序。(第0项是 "a", 第一项是 72)

sorted_score= sorted(score.items(), key = lambda x: x[1])print(sorted_score) # ('a', 72), ('x', 75), ('c', 81), ('y', 84), ('z', 93), ('b', 97)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值