Home > Backend Development > Python Tutorial > Python introduction list.sort method and built-in function sorted

Python introduction list.sort method and built-in function sorted

coldplay.xixi
Release: 2021-01-18 17:11:34
forward
3609 people have browsed it

Python introduction list.sort method and built-in function sorted

Related free learning recommendations: python video tutorial

Python list sorting list.sort method and built-in function sorted

Many times after we get a list, this list does not meet our needs. What we need is a special order List.

At this time, you can use the list.sort method and the built-in function sorted. This article introduces the usage and difference between the list.sort method and the sorted built-in function.

1. list.sort method

The list.sort method sorts the list in place, which means it does not make a copy of the original list. This is why the return value of this method is None, reminding you that this method will not create a new list.

Returning None in this case is actually a convention in Python: if a function or method changes the object in place, it should return None so that the caller knows the parameters passed in. Changes have occurred and no new objects have been created.

Let’s take a look at the code:

# coding=utf-8
list_a = [1, 2, 8, 3, 7, 9, 5, 7]
# sort()方法没有返回值
list_b = list_a.sort()
print("list_a: ", list_a)
print('list_b: ', list_b)
Copy after login

Running results:

list_a:  [1, 2, 3, 5, 7, 7, 8, 9]
list_b:  None
Copy after login

Returning None to indicate in-place changes has a drawback to this convention, that is, the caller cannot concatenate it stand up. On the contrary, methods that return a new object can be chained to form a coherent interface.

2. Sorted built-in function

Contrary to list.sort, the built-in function sorted will create a new list as the return value.

This method can accept any form of iterable object as a parameter, even immutable sequences or generators, and regardless of the parameters sorted accepts, it will eventually return a list.

Code example:

list_c = [1, 2, 8, 3, 7, 9, 5, 7]
# sorted内置函数会返回一个排序后的新列表
list_d = sorted(list_c)
print("list_c: ", list_c)
print('list_d: ', list_d)
Copy after login

Running result:

list_c:  [1, 2, 8, 3, 7, 9, 5, 7]
list_d:  [1, 2, 3, 5, 7, 7, 8, 9]
Copy after login

It can be seen that when using the built-in function sorted, a new list is returned, but the original list has not changed.

This has two benefits:

1. If we need to use both the original list and the sorted list, or we want to sort a non-list iterable object into Both list and sorted can be done

2. When there is a return value, we can make chain calls

# 可以对非列表的可迭代对象排序生成列表
str_e = 'python'
list_e = sorted(str_e)
print(list_e)

# 链式调用
str_f = '-'.join(sorted(str_e)).upper().split('-')
print(str_f)
Copy after login

Running results:

['h', 'n', 'o', 'p', 't', 'y']
['H', 'N', 'O', 'P', 'T', 'Y']
Copy after login

3. Keywords Parameters key and reverse

Whether it is the list.sort method or the sorted function, there are two optional keyword parameters:

key
Receives a function with only one parameter. This function will be used on each element in the sequence, and the result will be the comparison key that the sorting algorithm relies on.

For example, when sorting some strings, you can use key=str.lower to achieve sorting that ignores case, or use key=len to sort based on string length. The default value of key is the identity function, which means that the element's own value is used by default to sort.

reverse:

If set to True, the elements in the sorted sequence will be output in descending order (that is, the maximum value will be regarded as the minimum value) Sorting), the default value of reverse is False.

phone = ('HUAWEI', 'OPPO', 'MI', 'MEIZU', 'VIVO')
# 按长度进行排序
phone_list = sorted(phone, key=len)
print(phone_list)

phone_list_re = sorted(phone, key=len, reverse=True)
print(phone_list_re)
Copy after login

Running results:

['MI', 'OPPO', 'VIVO', 'MEIZU', 'HUAWEI']
['HUAWEI', 'MEIZU', 'OPPO', 'VIVO', 'MI']
Copy after login

In the above code, the first sort creates a new string list sorted by length. The second sorting is to change the sorting by length from ascending order to descending order.

If you are careful, you should be able to find that the second result is not a complete flip of the first sorted result.

The lengths of OPPO and VIVO are both 4. After reverse=True, their relative positions are the same as the first sorting. What is the reason for this?

The sorting algorithm behind sorted and list.sort is Timsort. It is an adaptive algorithm that alternately uses insertion sort and merge sort
according to the order characteristics of the original data to achieve the best efficiency.

Python's sorting algorithm Timsort is stable (just know this), which means that even if the two elements are incomparable in size, their relative positions are fixed in the result of each sort.

Because the sorting algorithm used is stable, that is to say, when the lengths are the same, the relative positions of OPPO and VIVO will not change.

Regarding the use of the list.sort() method and the sorted built-in function, I have now mastered it~

Related free learning recommendations: python tutorial (video)

The above is the detailed content of Python introduction list.sort method and built-in function sorted. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:csdn.net
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template