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

1.为元组中元素命名

方法1.定义常量

NAME, AGE =  0, 1

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

name = student[NAME]
age = student[AGE]

方法2.使用 namedtuple

from collections import namedtuple

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 in lis:
    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 import Counter

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)

 

posted @ 2018-11-28 15:56  王不惑  阅读(715)  评论(0编辑  收藏  举报