Python 列表的sort()方法之高级排序
2017-11-05 16:16
405 查看
列表的sort()排序方法,默认是升序。
def my_key1(x):
return x%10 #返回个位数值
def my_key2(x):
return x[1] #返回序列的第二个元素
x=[8,13,5,2,5,16,1,4]
y=[['xiaoming',13],['xiaohong',12],['zhangsan',17],['lisi',20],['wangwu',16],]
x.sort(key=my_key1) #按个位数大小排序
print x
y.sort(key=my_key2) #按列表第二个元素值排序,再次表示年龄
print y
sort()方法的第三个可选参数reverse,是个布尔类型,用非零表示TRUE,0表示False,为TRUE时表示降序排列
>>> x=[8,13,5,2,5,16,1,4]
>>> x.sort(reverse=True)
>>> x
[16, 13, 8, 5, 5, 4, 2, 1]
>>> x.sort(reverse=0)
>>> x
[1, 2, 4, 5, 5, 8, 13, 16]
>>> x=[8,3,5,2,5,6,1,4] >>> x.sort() >>> x [1, 2, 3, 4, 5, 5, 6, 8]sort()方法有三个可选参数cmp、key、reserve。cmp和key都属于内建函数,其中cmp采用升序排列,key值可以为len,int等
>>> x=[8,3,5,12,5,6,11,4] >>> x.sort(cmp) >>> x [3, 4, 5, 5, 6, 8, 11, 12] >>> y=['abc','bc','dsaas','a','cd'] >>> y.sort(key=len) >>> y ['a', 'bc', 'cd', 'abc', 'dsaas']自定义cmp比较函数,改变排序方式
def comp1(x,y): #实现降序排序,x值打印为:[8, 6, 5, 5, 4, 3, 2, 1] if x<y: return 1 else: return -1 def comp2(x,y): #实现按字符串长度降序排序,y值打印为:['dsaas', 'abc', 'cd', 'bc', 'a'] if len(x)<len(y): return -1 else: return 1 x=[8,3,5,2,5,6,1,4] y=['abc','bc','dsaas','a','cd'] x.sort(comp1) print x y.sort(comp2) print y自定义关键字key函数,改变排序方式
def my_key1(x):
return x%10 #返回个位数值
def my_key2(x):
return x[1] #返回序列的第二个元素
x=[8,13,5,2,5,16,1,4]
y=[['xiaoming',13],['xiaohong',12],['zhangsan',17],['lisi',20],['wangwu',16],]
x.sort(key=my_key1) #按个位数大小排序
print x
y.sort(key=my_key2) #按列表第二个元素值排序,再次表示年龄
print y
sort()方法的第三个可选参数reverse,是个布尔类型,用非零表示TRUE,0表示False,为TRUE时表示降序排列
>>> x=[8,13,5,2,5,16,1,4]
>>> x.sort(reverse=True)
>>> x
[16, 13, 8, 5, 5, 4, 2, 1]
>>> x.sort(reverse=0)
>>> x
[1, 2, 4, 5, 5, 8, 13, 16]
相关文章推荐
- Python 列表排序方法reverse、sort、sorted详解
- python 列表排序方法sort、sorted技巧篇(转自: aben)
- Python 列表排序方法reverse、sort、sorted详解
- python 列表排序方法reverse、sort、sorted基础篇
- Python 列表排序方法reverse、sort、sorted详解
- Python 列表排序方法reverse、sort、sorted详解
- Python 列表排序方法reverse、sort、sorted详解
- python列表排序方法sort、sorted技巧篇
- python 列表排序方法sort、sorted技巧篇
- Python 列表排序方法reverse、sort、sorted详解
- python中列表排序sort()方法或者内建函数sorted()
- Python 列表排序方法reverse、sort、sorted操作方法
- Python内置函数sorted()和列表方法sort()排序规则不得不说的事
- python 列表排序方法reverse、sort、sorted详解
- Python 列表排序方法reverse、sort、sorted详解
- Python 列表排序方法reverse、sort、sorted详解
- python 列表排序方法sort、sorted技巧篇
- Python对列表排序的方法实例分析
- Python实现二维数组按照某行或列排序的方法【numpy lexsort】
- python实现忽略大小写对字符串列表排序的方法