首页 > 代码库 > 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)]