码迷,mamicode.com
首页 > 其他好文 > 详细

sort counter 排序

时间:2014-06-16 00:32:05      阅读:216      评论:0      收藏:0      [点我收藏+]

标签:style   class   blog   code   java   http   

bubuko.com,布布扣
 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}]    
bubuko.com,布布扣

 

bubuko.com,布布扣
 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)]
bubuko.com,布布扣

 

sort counter 排序,布布扣,bubuko.com

sort counter 排序

标签:style   class   blog   code   java   http   

原文地址:http://www.cnblogs.com/xiaopythoner/p/3784162.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!