Python list sort () method

Examples
alphabetically sorted list:

cars = ['Porsche', 'BMW', 'Volvo']

cars.sort()

Definition and Usage
By default, sort () method of the list in ascending order.

You can also have a function to determine the sort criteria.

grammar:list.sort(reverse=True|False, key=myFunc)

parameter description
reverse Optional. reverse = True will list in descending order. The default is reverse = False.
key Optional. Function specifies the sort criteria.

Example 1
list in descending order:

cars = ['Porsche', 'BMW', 'Volvo']

cars.sort(reverse=True)

Example 2
sorts the list according to the length value:

# 返回值的长度的函数:
def myFunc(e):
  return len(e)

cars = ['Porsche', 'Audi', 'BMW', 'Volvo']

cars.sort(key=myFunc)

Example 3
sorts the list according to dictionary "year" value dictionary:

# 返回 'year' 值的函数:
def myFunc(e):
  return e['year']

cars = [
  {'car': 'Porsche', 'year': 1963},
  {'car': 'Audi', 'year': 2010},
  {'car': 'BMW', 'year': 2019},
  {'car': 'Volvo', 'year': 2013}
]

cars.sort(key=myFunc)

Example 4
list in descending order according to the length value:

# 返回值的长度的函数:
def myFunc(e):
  return len(e)

cars = ['Porsche', 'Audi', 'BMW', 'Volvo']

cars.sort(reverse=True, key=myFunc)
Published 186 original articles · won praise 21 · views 10000 +

Guess you like

Origin blog.csdn.net/sinat_23971513/article/details/105288254