source.txt: 60行
89
91
93
90
92
92
94
92
89
95
93
92
90
92
93
94
94
92
90
92
92
92
...
统计各个值的百分比,并排序
# -*- coding: gbk -*- with open(r'F:source.txt','r') as f: lines=f.readlines() #print len(lines) print len(lines) dic={}; for age in lines: age=age.strip() if age not in dic.keys(): dic[age]=1 else: dic[age]+=1 print '统计各个值的总数:',dic total = sum(dic.values()) for key in dic.iterkeys(): dic[key]=(dic[key],float(dic[key])/total) print '统计总数和百分比:',dic dicnew={} li=[] for key in dic.iterkeys(): li.append((key,float("%0.2f"%dic[key][1]))) print '百分比格式化为两位小数:',li print '按值进行排序:',sorted(li,key=lambda item:item[0]) dic=dict(li) print '四舍五入之后的总百分比:',sum(dic.values()) #print li
输出:
60
统计各个值的总数: {'89': 4, '91': 4, '90': 9, '93': 10, '92': 25, '95': 2, '94': 6}
统计总数和百分比: {'89': (4, 0.06666666666666667), '91': (4, 0.06666666666666667), '90': (9, 0.15), '93': (10, 0.16666666666666666), '92': (25, 0.4166666666666667), '95': (2, 0.03333333333333333), '94': (6, 0.1)}
百分比格式化为两位小数: [('89', 0.07), ('91', 0.07), ('90', 0.15), ('93', 0.17), ('92', 0.42), ('95', 0.03), ('94', 0.1)]
按值进行排序: [('89', 0.07), ('90', 0.15), ('91', 0.07), ('92', 0.42), ('93', 0.17), ('94', 0.1), ('95', 0.03)]
四舍五入之后的总百分比: 1.01