Python中的sorted()函数

sorted()函数的主要用法

>>> list = [1,3,2,4]  #输入
>>> sorted(list) #输入
[1, 2, 3, 4]  #输出  默认升序排列
>>> sorted(list,reverse=True)#输入  #降序排列
[4, 3, 2, 1]  #输出
>>> sorted(list,key=lambda x:x[0],reverse=True)#输入 
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 1, in <lambda>
TypeError: 'int' object is not subscriptable                 #“str”和“int”的实例之间不支持
>>> list = [('b',1),('a',3),('d',2),('c',4)]#输入 
>>> sorted(list,key=lambda x:x[0],reverse=True)#输入 按第一个字符从大到小排列
[('d', 2), ('c', 4), ('b', 1), ('a', 3)]  #输出
>>> list = [('b',1),('a',3),('d',2),('c',4)] #输入
>>> sorted(list,key=lambda x:x[1],reverse=True)从大到小排列,按第二个字符排列
[('c', 4), ('a', 3), ('d', 2), ('b', 1)]
原文地址:https://www.cnblogs.com/CCCrunner/p/11781614.html