Detailed explanation of Python list sort() function

"Author's Homepage": Shibie Sanri wyx
"Author's Profile": CSDN top100, Alibaba Cloud Blog Expert, Huawei Cloud Share Expert, Network Security High-quality Creator
"Recommended Column": Xiaobai Zero Basic "Python Beginner to Master"

sort() can "sort" the list

grammar

list.sort( key, reverse )

parameter

  • key : (optional) specifies the collation
  • reverse : (optional) ascending descending order

return value

  • Returns None while sorting the original list. That is, there is no return value

Example: Sort the elements in a list

list1 = [1, 3, 2, 5]
list1.sort()
print(list1)

output:

[1, 2, 3, 5]

1. Ascending and descending

The reverse parameter controls the "ascending" and "descending" sorting , True means descending, False means ascending; the default is ascendingreverse=False

list1 = [1, 3, 2, 5]
list1.sort(reverse=True)
print(list1)
list1.sort(reverse=False)
print(list1)
list1.sort()
print(list1)

output:

[5, 3, 2, 1]
[1, 2, 3, 5]
[1, 2, 3, 5]

2. The difference between sort() and sorted()

Receive the return value of sort() , which can be found to be None

list1 = [1, 3, 2, 5]
list2 = list1.sort()
print(list2)

output:

None

Print the "memory address" before and after sorting , and you can find that the address has not changed

list1 = [1, 3, 2, 5]
print(id(list1))
list1.sort()
print(id(list1))

output:

2361470487744
2361470487744

The design idea of ​​sort() is to "modify" the original list instead of returning a new list;
it will not create a new list, thus saving "efficiency" ;
of course, this also means that the original list has been modified, so be careful when using it This point;
sorted() is an extension function of sort() , which can sort the elements of the list without modifying the original list.

list1 = [1, 3, 2, 5]
list2 = sorted(list1)
print(list1)
print(list2)

output:

[1, 3, 2, 5]
[1, 2, 3, 5]

As you can see from the results, sorted() creates a new list to hold the sorted list.


3. Slice sorting

Copying the "slice" of the original list to the new list, and then sorting the new list, can also achieve sorting without changing the original list.

list1 = [1, 3, 2, 5]
list2 = list1[:]
list2.sort()
print(list1)
print(list2)

output:

[1, 3, 2, 5]
[1, 2, 3, 5]

The direct "assignment" method is not acceptable, because if you assign a value, the two lists will point to the same memory address, and the original list will change synchronously.

list1 = [1, 3, 2, 5]
list2 = list1
list2.sort()
print(list1)
print(list2)

output:

[1, 2, 3, 5]
[1, 2, 3, 5]

4. Specify the sorting rules

The key parameter can specify sorting "rules"

4.1, sort by string length

For a "list" whose elements are all strings , it can be sorted by the "length" of the string

list1 = ['aaaaa', 'aa', 'aaaa', 'a']
list1.sort(key=len)
print(list1)

output:

['a', 'aa', 'aaaa', 'aaaaa']

Essentially, the len() function of the string is used to calculate the length and then sorted. If there is no element in the int column without the len() function, an error TypeError: object of type 'int' has no len() will be reported.

insert image description here


4.2, sort by the second character

For a list whose elements are all strings, it can be sorted according to the "character" of the element .

list1 = ['cb', 'fa', 'zd', 'ec']
list1.sort(key=lambda x: x[1])
print(list1)

output:

['fa', 'cb', 'ec', 'zd']

It should be noted that the character length of all elements must be sufficient. For example, if an element has only one character but is sorted according to the second character, if the function cannot find the second character, an error will be reported IndexError: string index out of range

insert image description here


4.3. Find the nth largest element

Descending first, and then taking the value according to the "index" , you can get the first or second largest value in the list, etc.

list1 = [4, 3, 9, 6, 1]
list1.sort(reverse=True)
print('最大的元素:', list1[0])
print('第二大的元素:', list1[1])

output:

最大的元素: 9
第二大的元素: 6

5. Other types of sorting

sort() can only sort lists, and sorted() can sort iterable objects; therefore, if you want to sort strings, tuples, dictionaries, etc., you can use sorted()

str1 = "312"
print(sorted(str1))

tuple1 = (5, 1, 3)
print(sorted(tuple1))

dict1 = {
    
    "key1": 1, "key2": 2}
print(sorted(dict1))

output:

['1', '2', '3']
[1, 3, 5]
['key1', 'key2']

From the output results, it can be found that after the string, tuple, and dictionary types are sorted, the returned list type is; and the dictionary only sorts the keys, not the values.

Guess you like

Origin blog.csdn.net/wangyuxiang946/article/details/131625625