list
1 #按照list的第二键值排序 disP2P = [[1,2,3],[2,3,4],[4,5,6]] 2 disP2P = sorted(disP2P,key = lambda x:x[2])
1 student_tuples = [ 2 ('john', 'A', 15), 3 ('jane', 'B', 12), 4 ('dave', 'B', 10), 5 ] 6 sorted(student_tuples, key=lambda student: student[2]) # sort by age 7 [('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)]
1 class Student: 2 def __init__(self, name, grade, age): 3 self.name = name 4 self.grade = grade 5 self.age = age 6 def __repr__(self): 7 return repr((self.name, self.grade, self.age)) 8 student_objects = [ 9 Student('john', 'A', 15), 10 Student('jane', 'B', 12), 11 Student('dave', 'B', 10), 12 ] 13 >>> sorted(student_objects, key=lambda student: student.age) # sort by age 14 #[('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)]
dir
1 sorted(d.items(),key = lambda x:x[1],reverse = True)
多个list同时排序
1 #变成元组list的形式,然后对list排序再恢复回来 2 tmlist = [] 3 for l in range(n): 4 tmlist = tmlist + [(X[l][i],y[l],w[l])] 5 tmlist =sorted(tmlist,key = lambda x: x[0]) 6 XX = [] 7 W = [] 8 Y = [] 9 for l in range(n): 10 XX = XX+[tmlist[l][0]] 11 Y = Y + [tmlist[l][1]] 12 W = W + [tmlist[l][2]]