一、lambda推导式
tuples = [(1, 'c'), (2, "d"), (3, 'a'), (4, 'c')]
ret = sorted(tuples,key=lambda x:x[1]) ret1 = sorted(tuples,key=lambda x:x[0]) print("打印ret结果:",ret) print("打印ret1结果:",ret1) tuples3 = {'a': 'China', 'd': 'USA', 'b': 'Russia', 'g': 'Kanada','c':'Auster'} ret3 = sorted(tuples3.items(),key=lambda x :x[0]) ret4 = sorted(tuples3.items(),key=lambda x :x[1]) print("打印ret3结果:",ret3) print("打印ret4结果:",ret4)
结果:
二、列表腿导式
tuples = [(1, 'c'), (2, "d"), (3, 'a'), (4, 'c')]
ret5=[] for i in tuples: ret5.append(i) print("打印ret5结果:",sorted(ret5)) ret6=sorted([ i for i in tuples ]) print("打印ret6结果:",ret6) ret7=sorted([ i[1] for i in tuples ]) print("打印ret7结果:",ret7)
结果: