当前位置:主页 > 软件编程 > Python代码 >

Python sorted排序方法如何实现

时间:2021-01-22 12:28:26 | 栏目:Python代码 | 点击:

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

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

sorted定义如下:

问题描述:

给定列表如下:

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))

您可能感兴趣的文章:

相关文章