sorted排序的两个方法 - Python

在给列表排序时,sorted非常好用,语法如下:

 

sorted(iterable[, cmp[,key[,reverse]]])

 

简单列表排序,很容易完成,sorted(list)返回的对象就是列表结果,但是遇到列表中嵌套元组时,需要使用特殊的方法解决。

 

问题描述:

给定列表如下:

list_example = [('John', 35), ('Jack', 32), ('Michael', 28), ('Sean', 20)]

输出要求:

[('Sean', 20), ('Michael', 28), ('Jack', 32), ('John', 35)]

 

解决方法:

1. 传入函数给key,完成操作;

2. 直接使用lambda函数;

 

方法1的代码如下:

def revsort(oldlist):
    return oldlist[::-1]

def by_age(li):
    return sorted(li, key = revsort)

方法2的代码如下:

def by_age(li):
    return sorted(li, key = lambda x: x[1])
 
直接print可以得到结果:
print(by_age(list_example))

 

posted @ 2020-03-27 22:19  Johnthegreat  阅读(291)  评论(0编辑  收藏  举报