码迷,mamicode.com
首页 > 编程语言 > 详细

Python sorted

时间:2016-06-12 20:30:41      阅读:275      评论:0      收藏:0      [点我收藏+]

标签:

Python中有有两种方法进行List排序:

1. 用List的成员函数sort进行排序;

2. 用built-in函数sorted进行排序(从2.4开始);

API:

sort

技术分享

sorted

技术分享

iterable:是迭代的类型;

cmp:用于比较的函数,具体比较,由key决定,有默认值,迭代集合中的一项;

key:用列表元素的某个属性和函数进行作为关键字,有默认值,迭代集合中的一项;

reverse:为True是正序,为False是反序;

备注:key和cmp,可以使用lambda表达式;

 

Sort Reverse

True

1 >>> list=[5, 2, 3, 1, 4]
2 >>> print sorted(list,reverse=True)
3 [5, 4, 3, 2, 1]

False

1 >>> list=[5, 2, 3, 1, 4]
2 >>> print sorted(list,reverse=False)
3 [1, 2, 3, 4, 5]

Sort cmp

1 >>> L=[(b,2),(c,3),(a,1),(d,4)]
2 >>> print sorted(L, cmp=lambda x,y:cmp(x[1],y[1]))
3 [(a, 1), (b, 2), (c, 3), (d, 4)]

Sort key

1 >>> L=[(b,2),(c,3),(a,1),(d,4)]
2 >>> print sorted(L, key=lambda x:x[1])
3 [(a, 1), (b, 2), (c, 3), (d, 4)]

备注:key的效率比cmp高

例子:

 

import math
import os

his = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 , 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 2, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 2, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 2, 1, 0, 0, 0, 2, 0, 0, 0, 0, 1, 0, 1, 1, 0, 0 , 1, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 0, 0, 0, 1, 2, 0, 1, 0, 0, 1, 0, 2, 0, 0, 1, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 1, 0, 3, 1, 3, 3, 0, 0, 0, 0, 0, 0, 1, 0, 3, 2, 132, 1, 1, 0, 0, 0, 1, 2, 0, 0, 0, 0, 0, 0, 0, 15, 0 , 1, 0, 1, 0, 0, 8, 1, 0, 0, 0, 0, 1, 6, 0, 2, 0, 0, 0, 0, 18, 1, 1, 1, 1, 1, 2, 365, 115, 0, 1, 0, 0, 0, 135, 186, 0, 0, 1, 0, 0, 0, 116, 3, 0, 0, 0, 0, 0, 21, 1, 1, 0, 0, 0, 2, 10, 2, 0, 0, 0, 0, 2, 10, 0, 0, 0, 0, 1, 0, 625]

values = {}

for i in range(256):
    values[i] = his[i]

for j,k in sorted(values.items(),key=lambda x:x[1],reverse = True)[:10]:
    print j,k

 

Python sorted

标签:

原文地址:http://www.cnblogs.com/sxmcACM/p/5578612.html

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