zoukankan      html  css  js  c++  java
  • 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

  • 相关阅读:
    Codeforces Round #475 (Div. 1) B. Destruction of a Tree
    HDU
    HihoCoder
    浅谈spfa几个优化
    Codeforces Round #474 E. Alternating Tree
    Wannafly 挑战赛12 D
    2017 Multi-University Training Contest
    2017 Multi-University Training Contest
    斜率优化DP基础XVI Open Cup named after E.V. Pankratiev. GP of Ukraine.K
    斜率优化DP入门_HDU3507_Print Article
  • 原文地址:https://www.cnblogs.com/aaronhoo/p/5783812.html
Copyright © 2011-2022 走看看