python排序 sorted()与list.sort() (转)
该文章为转载;原文地址为:https://www.cnblogs.com/zuizui1204/p/6422939.html
https://www.runoob.com/python/python-func-sorted.html
1、sort 与 sorted 区别:
sort 是应用在 list 上的方法,sorted 可以对所有可迭代的对象进行排序操作。
list 的 sort 方法返回的是对已经存在的列表进行操作,无返回值,而内建函数 sorted 方法返回的是一个新的 list,而不是在原来的基础上进行的操作
2、示例
# 1. 基础类型 a = [5,7,6,3,4,1,2] b = sorted(a) # 保留原列表 print(a) # [5, 7, 6, 3, 4, 1, 2] print(b) #[1, 2, 3, 4, 5, 6, 7] # 2.复杂类型 students = [('john', 'A', 15), ('jane', 'B', 12), ('dave', 'B', 10)] # [('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)] sorted(students, key=lambda s: s[2]) # 按年龄排序 #[('john', 'A', 15), ('jane', 'B', 12), ('dave', 'B', 10)] sorted(students, key=lambda s: s[2], reverse=True) # 按降序 3、类,同2 class Student: def __init__(self, name, score): self.name = name self.score = score students = [Student('john', 90.0), Student('jane', 70.0), Student('dave', 92.0)] sorted(students, key=lambda s: s.score) # 按score排序
# 4.多key排序
# https://www.jianshu.com/p/d1a26a9a2496
student_tuples = [ {'name': 'John', 'grade': 'A', 'no': 1}, {'name': 'Dave', 'grade': 'C', 'no': 2}, {'name': 'Leon', 'grade': 'B', 'no': 3}, ] # 按name、grade升序排 print sorted(student_tuples, key=lambda x: (x['name'], x['grade']))
# 按name升序、grade降序print sorted(student_tuples, key=lambda x: (x['name'], -x['grade']))