list.sort(key=**):sort 对列表进行排序,是对原序列排序,不生成新的列表。
students = [['zhangsan', 'B', 85], ['lisi', 'C', 90], ['wangwu', 'A', 88]] # 可以
# students = [('zhangsan', 'B', 85), ('lisi', 'C', 90), ('wangwu', 'A', 88)] # 可以
# students = (['zhangsan', 'B', 85], ['lisi', 'C', 90], ['wangwu', 'A', 88]) # 报错
# students = (('zhangsan', 'B', 85), ('lisi', 'C', 90), ('wangwu', 'A', 88)) # 报错
print(students, id(students))
students.sort(key=lambda x: x[0][-1]) # 按照名字末尾字符升序排列
print(students, id(students))
students.sort(key=lambda x: x[1]) # 按照等级升序排列
print(students, id(students))
students.sort(key=lambda x: x[2], reverse=True) # 按照分数降序排列
print(students, id(students))
依次返回:
[['zhangsan', 'B', 85], ['lisi', 'C', 90], ['wangwu', 'A', 88]] 1168182589568
[['lisi', 'C', 90], ['zhangsan', 'B', 85], ['wangwu', 'A', 88]] 1168182589568
[['wangwu', 'A', 88], ['zhangsan', 'B', 85], ['lisi', 'C', 90]] 1168182589568
[['lisi', 'C', 90], ['wangwu', 'A', 88], ['zhangsan', 'B', 85]] 1168182589568
sorted(seq, key=**):sorted 对序列进行排序,生成新的序列。
# students = [['zhangsan', 'B', 85], ['lisi', 'C', 90], ['wangwu', 'A', 88]] # 可以
# students = [('zhangsan', 'B', 85), ('lisi', 'C', 90), ('wangwu', 'A', 88)] # 可以
# students = (['zhangsan', 'B', 85], ['lisi', 'C', 90], ['wangwu', 'A', 88]) # 可以
students = (('zhangsan', 'B', 85), ('lisi', 'C', 90), ('wangwu', 'A', 88)) # 可以
print(students, id(students))
student1 = sorted(students, key=lambda x: x[0][-1]) # 按照名字末尾字符升序排列
print(student1, id(student1))
student2 = sorted(students, key=lambda x: x[1]) # 按照等级升序排列
print(student2, id(student2))
student3 = sorted(students, key=lambda x: x[2], reverse=True) # 按照分数降序排列
print(student3, id(student3))
from operator import itemgetter
student4 = sorted(students, key=itemgetter(1), reverse=True) # 按照等级降序排列
print(student4, id(student4))
student5 = sorted(students, key=itemgetter(1, 2)) # 先按照等级降序排列,再按照分数兼续排列
print(student5, id(student5))
依次返回:
(('zhangsan', 'B', 85), ('lisi', 'C', 90), ('wangwu', 'A', 88)) 2099748351808
[('lisi', 'C', 90), ('zhangsan', 'B', 85), ('wangwu', 'A', 88)] 2099748305856
[('wangwu', 'A', 88), ('zhangsan', 'B', 85), ('lisi', 'C', 90)] 2099748584128
[('lisi', 'C', 90), ('wangwu', 'A', 88), ('zhangsan', 'B', 85)] 2099748584064
[('lisi', 'C', 90), ('zhangsan', 'B', 85), ('wangwu', 'A', 88)] 2099748583872
[('wangwu', 'A', 88), ('zhangsan', 'B', 85), ('lisi', 'C', 90)] 2099748342080