Python統計百分比及排序


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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM