


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)
Running results:
list_a: [1, 2, 3, 5, 7, 7, 8, 9] list_b: None
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)
Running result:
list_c: [1, 2, 8, 3, 7, 9, 5, 7] list_d: [1, 2, 3, 5, 7, 7, 8, 9]
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)
Running results:
['h', 'n', 'o', 'p', 't', 'y'] ['H', 'N', 'O', 'P', 'T', 'Y']
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)
Running results:
['MI', 'OPPO', 'VIVO', 'MEIZU', 'HUAWEI'] ['HUAWEI', 'MEIZU', 'OPPO', 'VIVO', 'MI']
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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

To run Python code in Sublime Text, you need to install the Python plug-in first, then create a .py file and write the code, and finally press Ctrl B to run the code, and the output will be displayed in the console.

Writing code in Visual Studio Code (VSCode) is simple and easy to use. Just install VSCode, create a project, select a language, create a file, write code, save and run it. The advantages of VSCode include cross-platform, free and open source, powerful features, rich extensions, and lightweight and fast.

VS Code can be used to write Python and provides many features that make it an ideal tool for developing Python applications. It allows users to: install Python extensions to get functions such as code completion, syntax highlighting, and debugging. Use the debugger to track code step by step, find and fix errors. Integrate Git for version control. Use code formatting tools to maintain code consistency. Use the Linting tool to spot potential problems ahead of time.

Running Python code in Notepad requires the Python executable and NppExec plug-in to be installed. After installing Python and adding PATH to it, configure the command "python" and the parameter "{CURRENT_DIRECTORY}{FILE_NAME}" in the NppExec plug-in to run Python code in Notepad through the shortcut key "F6".
