Definition:

The sorted() function sorts all iterable objects.

The sorted method, the built-in function, returns a new list rather than an operation on top of the original. The image of grammar:

Sorted the grammar:

sorted(iterable, cmp=None, key=None, reverse=False)

Return value: Returns the reordered list.

Parameter Description:

Iterable -- iterable. CMP -- the comparison function, which takes two arguments, both of which are taken from the iterable, and which must obey the rules that return 1 if greater than, -1 if less than, and 0 if equal. Key -- A comparison element that takes only one argument. The argument to the function is taken from the iterable, and an element in the iterable is specified for sorting. For both sort() and sorted() functions, passing in the key argument is more efficient than passing in the CMP argument. Reverse -- Collation, reverse = True descending, reverse = False ascending (default).Copy the code

The CMP () function is used to compare two objects, returning -1 if x < y, 0 if x == y, and 1 if x > y

Grammar:

cmp( x, y )

Parameters:

X -- numeric expression. Y -- numerical expression.Copy the code

The reverse() function: Used to reverse elements in a list.

Grammar:

list.reverse()

This method returns no value, but sorts the elements of the list backwards. Sorted sorted

1. By default, the sorted function sorts the sorted list in ascending order and returns a new list object, leaving the original list unchanged, the simplest sort.

>>> sorted(nums)[1, 2, 3,4,5]Copy the code

Reverse =True; reverse=True

        sorted(nums, reverse=True)[5, 4, 3, 2, 1]
Copy the code

Key is a function object, such as a list of strings. I want to sort by the length of the string

        chars = ['Andrew', 'This', 'a', 'from', 'is', 'string', 'test']>>> sorted(chars, key=len)['a', 'is', 'from', 'test', 'This', 'Andrew', 'string']
Copy the code

Len is a built-in function. The sorted function uses len to get the length of each string for sorting. Some people might use the anonymous function key=lambda x: len(x),

If a composite list structure, such as a list of tuples, is sorted by the second element in the tuple, lambda can be used to define an anonymous function.

        students = [('zhang', 'A'), ('li', 'D'), ('wang', 'C')]>>> sorted(students, key=lambda x: x[1])[('zhang', 'A'), ('wang', 'C'), ('li', 'D')]
Copy the code

This will be arranged in alphabetical order a-C-D.

If the elements to be sorted are custom classes, such as the Student class that sorts by age, it can be written as

A =,7,6,3,4,1,2 [5] > > > b = sorted # (a) retain the original list > > > a [5, 7, 6, 3, 4, 1, 2] > > > b [1, 2, 3, 4, 5, 6, 7] > > > L = [(" b ", 2), (' a ', 1), (' c ', 3), (' d ', 4)] > > > sorted (L, CMP = lambda x, y: CMP (x [1], [1]) y) # USES CMP function [(' a ', 1), (" b ", 2), (' c ', 3), (' d ', 4)] > > > sorted (L, key = lambda x: x [1]) # using key [(' a ', 1), (" b ", 2), (' c ', 3), (' d ', 4)] >>> students = [('john', 'A', 15), ('jane', 'B', 12), ('dave', 'B', 10)]>>> sorted(students, key=lambda s: S [2]) # sorted according to age [(' Dave ', 'B', 10), (' Jane ', 'B', 12), (' John ', 'A', 15)] > > > sorted (students, key = lambda s: S [2], reverse = True) # in descending order [(' John ', 'A', 15), (' Jane ', 'B', 12), (' Dave ', 'B', 10)] > > >Copy the code

5, Sorted by tuple like a database sort, sorted by multiple fields. For example, I sort by age first, and if age is the same, I sort by grade.

        sorted(student_objects, key=lambda t:(t.age, t.grade))[('dave', 'B', 10), ('lily', 'A', 12), ('jane', 'B', 12), ('john', 'A', 15)]
Copy the code

7. Similarly, there is a more efficient way to specify keys for custom classes

        from operator import attrgetter>>> sorted(student_objects, key=attrgetter('age'))[('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)]
Copy the code

What if there are two fields involved in sorting?

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

8. The previous sorting scenarios are based on the premise that two elements can be compared, for example, numerical values are compared by size, and letters are compared in order.

What if we have to define our own rules for comparison because they are not comparable?

Nums = [2, 1.5, 2.5, '2', '2.5']>>> sorted(nums)TypeError: '<' not supported between instances of 'STR' and 'int'Copy the code

A list of integers may have numbers, strings, and in Python3 strings and numbers cannot be compared, whereas in Python2 any type can be compared, which is a big difference between the two versions: Python2 >>> “2.5” > 2True# python3>>> “2.5” > 2TypeError: ‘>’ not supported between instances of ‘STR’ and ‘int’

The sorted function is different between Python2 and Python3 when it comes to data that requires a custom comparison operation:

In Python2, the sorted node can specify the CMP keyword argument, which can be achieved by CMP =compare,

Python3 also imports functools.cmp_to_key to implement the sorted() function.

Sort dictionaries (sort by dictionary value) multidimensional list sort dictionaries mixed list sort lists mixed dictionary sort stringsCopy the code

Sorted () and sorted()

1. Compared with sort(), sorted() has a wider range of functions, and their function forms are as follows:

sorted(iterable[, cmp[, key[, reverse]]]) s.sort([cmp[, key[, reverse]]])

2. Sorted () works on any iterable object, while sort() generally works on lists.

Traceback (most recent call last): File "<stdin>", line 1, in <module>AttributeError: 'tuple' object has no attribute 'sort'>>> sorted(a)[1, 2, 2, 3, 4]Copy the code

In the following example, using sort() for tuples raises AttributeError, whereas using sorted() does not.

3, when the sorting object is a list, they are suitable for different scenarios. The sorted() function returns a sorted list that remains the same; The sort() function modifies the list permanently and returns None.

A = [' 1 ', 1, 'a', 3, 7, 'n'] > > > sorted (a) [1, 3, 7, '1', 'a', 'n'] > > > a [' 1 ', 1, 'a', 3, 7, 'n'] > > > print a.s ort (None) > > > a [1, 3, 7, '1', 'a', 'n']Copy the code

If the original list needs to be preserved in the actual application process, sorted() is suitable; otherwise, sort() can be selected, because sort() does not need to copy the original list, consumes less memory and is efficient.

To learn more click: g.lgcoder.com/ad1/index.h…

Author: Programming Python