首页 > 代码库 > sort counter 排序
sort counter 排序
1 2 --------------------对象用Counter------------------------------------------------------------- 3 4 dc={"james":4,"kim":3,"marry":5,"bill":6} 5 from collections import Counter 6 counts=Counter(dc) 7 counts 8 >>Counter({‘bill‘: 6, ‘marry‘: 5, ‘james‘: 4, ‘kim‘: 3}) 9 counts.most_common(3) 10 >>[(‘bill‘, 6), (‘marry‘, 5), (‘james‘, 4)] 11 12 13 #-------------------数组用sorted operator ---------------------------------------------- 14 dc=[{‘name‘:"james",‘v‘:4},{‘name‘:"kim",‘v‘:3},{‘name‘:"marry",‘v‘:5},{‘name‘:"bill",‘v‘:6}] 15 import operator 16 print dc 17 >>[{‘name‘: ‘bill‘, ‘v‘: 6}, {‘name‘: ‘james‘, ‘v‘: 4}, {‘name‘: ‘kim‘, ‘v‘: 3}, {‘name‘: ‘marry‘, ‘v‘: 5}] 18 print sorted(dc,key=operator.itemgetter("v"),reverse=True) 19 >>[{‘name‘: ‘bill‘, ‘v‘: 6}, {‘name‘: ‘marry‘, ‘v‘: 5}, {‘name‘: ‘james‘, ‘v‘: 4}, {‘name‘: ‘kim‘, ‘v‘: 3}]
1 # ----Counter 可用于频次统计 2 ar=[1,2,2,3,5,6,6,5,5,6] 3 counts=Counter(ar) 4 print counts 5 >>Counter({5: 3, 6: 3, 2: 2, 1: 1, 3: 1}) 6 #输出是个对象 7 for k in counts: 8 print str(k)+" "+str(counts[k]) 9 >> 10 1 1 11 2 2 12 3 1 13 5 3 14 6 3 15 16 print counts.most_common() 17 >>[(5, 3), (6, 3), (2, 2), (1, 1), (3, 1)]
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。