list.sort( key=None, reverse=False)
#list就是咱们须要排序的列表;
#key:具体的函数的参数就是取自于可迭代对象中,指定可迭代对象中的一个元素来进行排序。
#reverse :True 降序,False 升序(默认)
def takeSecond(elem): print(elem[1]) return elem[1] # 列表 random = [(2, 2), (3, 4), (4, 1), (1, 3)] # 指定第二个元素排序 random.sort(key=takeSecond) # 输出类别 print ('排序列表:', random)
#output
2 4 1 3 排序列表: [(4, 1), (2, 2), (1, 3), (3, 4)] #就是按照列表里边的元组的第二个元素进行排序
sorted 与 sort的区别:html
#sort是在list上的方法,而sorted能够应用在任何可迭代对象; #sort是在原有列表上操做,sorted是返回一个新的列表 #sorted(iterable, key=None, reverse=False)
>>> a = [5,2,3,1,4] >>> a.sort() >>> a [1, 2, 3, 4, 5] #在原有列表上操做 >>> a.sorted() Traceback (most recent call last): File "<pyshell#3>", line 1, in <module> a.sorted() AttributeError: 'list' object has no attribute 'sorted' >>> sorted([5,2,3,1,4]) [1, 2, 3, 4, 5]#产生一个新列表 >>>
参考网址:python
https://www.runoob.com/python3/python3-func-sorted.htmlshell
https://www.runoob.com/python3/python3-att-list-sort.htmldom