python杂记——sort和sorted

python中有两种排序的方式sort和sorted。我们简单介绍一下。

sort是list的方法,它可以直接修改列表,返回值是None。sorted是python的内置函数,它从一个可迭代的对象构建一个新的排序后的列表。list.sort()是专门为列表定义的,而sorted可以接受任何可迭代对象。

排序是稳定的,也就是说当多个记录具有相同值时,将保留其原始排序。

> a = sorted([5,2,3,1,4])
> a
> [1,2,3,4,5]
> b = sorted({
    
    6:'D', 2:'B', 3:'B', 4:'E', 5:'A'})
> b
> [2,3,4,5,6]
> a = [5,2,3,1,4]
> a.sort()
> a
> [1,2,3,4,5]

指定排序的key

> student = [
('john', 'A', 15),
('jane', 'B', 12),
('dave', 'B', 10),
]
> a = sorted(student, key = lambda student:student[2])
> a
> [('dave', 'B', 10),('jane', 'B', 12),('john', 'A', 15),]
> a.sort(key = lambda a:a[1])
> a
> [('john', 'A', 15),('dave', 'B', 10),('jane', 'B', 12),]
> class Student:
...    def __init__(self, name, grade, age):
...        self.name = name
...        self.grade = grade
...        self.age = age
...    def __repr__(self):
...        return repr((self.name, self.grade, self.age))

> student_obj = [
...    Student('john', 'A', 15),
...    Student('jane', 'B', 12),
...    Student('dave', 'B', 10),
]
> a = sorted(student_obj, key=lambda student_obj: student_obj.age)
> a
>  [('dave', 'B', 10),('jane', 'B', 12),('john', 'A', 15),]

使用Operator模块函数

> from operator import itemgetter, attrgetter
> a = sorted(student, key=itemgetter(2)
> a
>  [('dave', 'B', 10),('jane', 'B', 12),('john', 'A', 15),]
> b = sorted(student_obj, key=attrgetter('age')
> b
>  [('dave', 'B', 10),('jane', 'B', 12),('john', 'A', 15),]
>  aa = sorted(student, key=itemgetter(1, 2) # 先按grade排序再按照age排序
>  aa
>  [('john', 'A', 15),('dave', 'B', 10),('jane', 'B', 12),]
>  bb = sorted(student_obj, key=attrgetter('grade', 'age')
>  bb
>   [('john', 'A', 15),('dave', 'B', 10),('jane', 'B', 12),]

升序和降序

list.sort()和sorted函数接受布尔值参数reverse,用于标记降序排序。

> a = sorted(student, key = lambda student:student[2], reverse=True)
> a
>  [('john', 'A', 15),('jane', 'B', 12),('dave', 'B', 10),]

猜你喜欢

转载自blog.csdn.net/itlilyer/article/details/120678272