python内置函数sorted

Source
import random
from icecream import ic
'''
sort(iterable,key=None,reverse=False) 默认值
Return a new list返回一个新列表 containing all items from the iterable in ascending order.升序
A custom key function(自定义的键函数) can be supplied to customize the sort order, and the
reverse flag can be set to request the result in descending order.
'''
# list.sort()无返回值,对原数据进行排序
# sorted()有返回值,返回排序备份

list1 = [1, 3, -2, -6, 9, 0, 16, -8, -5]
ic(list1.sort())  # 无返回值
ic(list1)  # 对原数据进行排序
random.shuffle(list1)  # 随机打乱列表的元素,使列表重新排列
ic(list1)
list2 = sorted(list1)  # 升序排列,原列表不变
ic(list2)
ic(list1)
list3 = sorted(list1, reverse=True)  # 降序排列
ic(list3)
ic(list1)
list4 = sorted(list1, key=lambda x: (x < 0))  # 满足条件x<0的往右边放,其余不变
ic(list4)
list5 = sorted(list1, key=lambda x: (x < 0, abs(x)))  # 满足条件x<0的往右边放,左右两侧再各自按绝对值的大小排列,默认为自然顺序(升序)
ic(list5)
list6 = sorted(list1, key=lambda x: (x < 0, abs(x)), reverse=True)
ic(list6)


'''面向对象中元素的排列'''
class Student:
    def __init__(self, name, age, sex):
        self.name = name
        self.age = age
        self.sex = sex


s1 = Student('x熊大', 8, 'M')
s2 = Student('l乐迪', 5, 'F')
s3 = Student('q巧虎', 1, 'M')
s4 = Student('y雅煊', 3, 'F')
list_s = [s1, s2, s3, s4]
for stu in list_s:
    ic(stu.name, stu.age, stu.sex)
list_s2 = sorted(list_s, key=lambda x: x.age)  # 按年龄升序排列对象列表
for stu in list_s2:
    ic(stu.age, stu.name, stu.sex)
list_s3 = sorted(list_s, key=lambda x: (x.sex, x.name))  # 先按性别排列,再按姓名排列
for stu in list_s3:
    ic(stu.sex, stu.name, stu.age)

在这里插入图片描述