python中的list排序

本文是阅读python文档笔记,地址:https://docs.python.org/3/howto/sorting.html
内容:
  • Python中有内置方法list.sort(),这个方式是会改变原来的list,也有内置函数sorted(),这个函数会返回一个新的list。文章主要讲各种方式排序数据in Python。
  • list.sort()方法仅仅只为list定义,而sorted()函数可以接受任何可以迭代的对象。
>>>sorted({1: 'D', 2: 'B', 3: 'B', 4: 'E', 5: 'A'})
>>>[1, 2, 3, 4, 5]
  • list.sort()和sorted()都有key参数,指定排序规则。这个参数接收的应该是一个函数,如下lambda
>>> sorted("This is a test string from Andrew".split(), key=str.lower)
>>> ['a', 'Andrew', 'from', 'is', 'string', 'test', 'This']
>>> student_tuples = [
         ('john', 'A', 15),
         ('jane', 'B', 12),
         ('dave', 'B', 10),
     ]

>>> sorted(student_tuples, key=lambda student: student[2])   # sort by age
[('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)]

>>> 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_objects = [
         Student('john', 'A', 15),
         Student('jane', 'B', 12),
         Student('dave', 'B', 10),
     ]
     
>>> sorted(student_objects, key=lambda student: student.age)   # sort by age
[('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)]
  • Operator Module Functions:python提供了几个非常方便的函数来获取key参数—itemgetter、attrgetter、 methodcaller
>>> from operator import itemgetter, attrgetter

>>> sorted(student_tuples, key=itemgetter(2))
[('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)]

>>> sorted(student_objects, key=attrgetter('age'))
[('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)]

>>> sorted(student_tuples, key=itemgetter(1,2))
[('john', 'A', 15), ('dave', 'B', 10), ('jane', 'B', 12)]

>>> sorted(student_objects, key=attrgetter('grade', 'age'))
[('john', 'A', 15), ('dave', 'B', 10), ('jane', 'B', 12)]
  • list.sort()和sorted()还有一个reserve参数,它是一个boolean值
>>> sorted(student_tuples, key=itemgetter(2), reverse=True)
[('john', 'A', 15), ('jane', 'B', 12), ('dave', 'B', 10)]

>>> sorted(student_objects, key=attrgetter('age'), reverse=True)
[('john', 'A', 15), ('jane', 'B', 12), ('dave', 'B', 10)]

你可能感兴趣的:(Python)