Detailed Explanation of the Application of python3 sort sorted Function

  • 2021-07-03 00:31:32
  • OfStack

python3 sorted removes support for cmp.

python3 Help Documentation:


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

key accepts one function, which accepts only one element, and defaults to None

reverse is a Boolean value. If set to True, the list elements will be arranged in reverse order, and the default is False

The working principle of key is emphatically introduced:

key specifies a function that takes one argument and extracts one key from each element for comparison. The default value is None.

Example 1:


students = [('john', 'A', 15), ('jane', 'B', 12), ('dave','B', 10)]

sorted(students,key=lambda s: x[2]) # Sort by age 

Results: [('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)]

Example 2: This is a string sort, and the collation rule is lowercase < Capitalized < Odd number < Even number


s = 'asdf234GDSdsf23' # Sort : Lowercase - Capitalized - Odd number - Even number 

print("".join(sorted(s, key=lambda x: (x.isdigit(),x.isdigit() and int(x) % 2 == 0,x.isupper(),x))))

Principle: First compare the first value of tuples, FALSE < TRUE, if equal, compare the next 1 value of the tuple, and so on.

First look at the sorting of Boolean value under 1:

print(sorted([True,Flase]))=== > Results [False, True]

The ranking of Boolean will put False first and True second.

1. x. The function of isdigit () is to put numbers before and letters after.

2. x. isdigit () and int (x)% 2 = = 0 ensures that odd numbers come first and even numbers come last.

3. x. isupper () is used to ensure that letters are lowercase before uppercase before uppercase.

4. The final x indicates that all categories are numerically or alphabetically sorted on the basis of the previous one.

Final result: addffssDGS33224

Example 3: 1 to interview questions:


list1=[7, -8, 5, 4, 0, -2, -5]

# Requirements 1. Positive numbers come before negative numbers come after  2. Integer from small to large  3. Negative numbers from big to small 

sorted(list1,key=lambda x:(x<0,abs(x)))

Problem-solving ideas: first, according to the positive and negative row, and then according to the size row.


Related articles: