为元组的每个元素命名
1 为元组的每个项目命名,提高程序的可读性 2 #定义一系列数据变量 3 4 #分别赋值为0,1,2,3 5 NAME,SEX,AGE,SCHOOL = range(4) 6 7 student = ('黄晓明','male', 42, '北京电影学院') 8 print(student[NAME]) 9 #黄晓明 10 11 12 #用标准库中的collections.namedtuple替代内置tuple 13 from collections import namedtuple 14 15 Student = namedtuple('Student',['name','age','sex','school']) 16 17 c位置传参 18 s = Student('黄晓明', 42, 'male', '北京电影学院') 19 print(s) 20 #Student(name='黄晓明', age=42, sex='male', school='北京电影学院') 21 22 #以类对象形式访问 23 print(s.name) 24 #黄晓明 25 26 #关键字传参,一一对应 27 s1 = Student(name='黄晓明',age=42,sex='male',school='北京电影学院') 28 print(s1) 29 #Student(name='黄晓明', age=42, sex='male', school='北京电影学院') 30 print(s1.name) 31 #黄晓明
1 统计序列中元素出现的频度 2 3 # 在随机序列中,找到出现次数最高的3个元素与其出现次数 4 from random import randint 5 from collections import Counter 6 7 data = [randint(0,10) for i in range(8)]
8 #将字典value初始化为0 9 c = dict.fromkeys(data, 0) 10 print(c) 11 #{9: 0, 7: 0, 5: 0, 1: 0, 6: 0, 2: 0, 3: 0} 12 13 for x in data: 14 c[x] += 1 15 print(c) 16 #计算出各个key产生的次数 17 #{9: 2, 7: 1, 5: 1, 1: 1, 6: 1, 2: 1, 3: 1} 18
19 #按value值递增排序 20 r = Counter(data) 21 print(r) 22 #Counter({9: 2, 7: 1, 5: 1, 1: 1, 6: 1, 2: 1, 3: 1}) 23 24 #筛选出前三 25 c = r.most_common(3) 26 print(c) 27 #[(9, 2), (7, 1), (5, 1)]