python

python - how to sort

  1.  overview

  2. Key function (★★★★★)

  3.  OPerator module functions

  4. asc and desc 升序和降序


Overview

对于python 列表,有一个方法 list.sort()  ,另外还有一个内置函数sorted()

list.sort() 是对本身排序,不会产生新的对象。而sorted 接收一个可迭代对象,返回一个新的排好序的list

Help on built-in function sorted in module builtins:

sorted(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
>>> help(list.sort)
Help on method_descriptor:

sort(...)
    L.sort(key=None, reverse=False) -> None -- stable sort *IN PLACE*

 list.sort() 会把原始列表修改,return None ,当你不需要原始列表的时候,这个方法会更有效率。

>>> a=[3,5,2,1]
>>> a.sort()
>>> a
[1, 2, 3, 5]


sorted()  这个方法用起来比较方便

 >>> sorted([6,3,8,12,4])
[3, 4, 6, 8, 12]
>>> 

 sorted() 接收可迭代对象

eg.

比如

>>> dic={4:'a',2:'b',3:'A',1:'h'}
>>> sorted(dic)
[1, 2, 3, 4]

Key function

Both list.sort() and sorted() have a key parameter to specify a function to be called on each list element
prior to making comparisons

list.sort()和sorted()都有一个关键参数来指定在每个列表元素上被调用的函数在进行比较之前。

for example:

>>> sorted("This is a test string from Andrew".split(), key=str.lower)
['a', 'Andrew', 'from', 'is', 'string', 'test', 'This']

The value of the key parameter should be a function that takes a single argument and returns a key to use
for sorting purposes. This technique is fast because the key function is called exactly once for each input
record

key 参数的值应该是一个函数对象,这个函数对象带一个参数,返回一个key,这个key 就是排序的标准,

 

class Student(object):
    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))


ls_grade = sorted([
    Student('join',90,15),
    Student('alex',87,13),
    Student('eleven',100,17)
    ],key=lambda stu:stu.grade)

ls_age = sorted([
    Student('join',90,15),
    Student('alex',87,17),
    Student('eleven',100,14)
    ],key=lambda stu:stu.age)

print(ls_grade)
print(ls_age)

 

 OPerator module functions



 

 

asc and desc 升序和降序

默认是升序排序

reverse 默认是false ,如果是true ,那就是降序排列

sorted 和list.sort() 的排序是稳定排序

于洋 回到顶部

原文地址:https://www.cnblogs.com/yuyang26/p/7859742.html