What is sorted in python

(*-*)浩
Release: 2019-06-22 11:32:35
Original
29767 people have browsed it

sorted is a built-in function of Python and is not a unique method of mutable objects (lists and dictionaries). The sorted() function requires a parameter (the parameter can be a list, dictionary, tuple, or string), regardless of No matter what parameters are passed, a return value with a list as the container will be returned. If it is a dictionary, a list of keys will be returned.

What is sorted in python

list: (Recommended learning: Python video tutorial)

>>> a = [4,3,7,8]
>>> sorted(a)
[3, 4, 7, 8]
>>> a
[4, 3, 7, 8]
Copy after login

That is, sorted meeting Returns a copy of the list, and at the same time changes the value of the original list and assigns the returned value to other variables.

dict:

>>> b = {1:'ab',2:'degg',4:'ght',9:'d'}
>>> sorted(b)
[1, 2, 4, 9]
>>> b
{1: 'ab', 2: 'degg', 4: 'ght', 9: 'd'}
Copy after login

That is, when sorted(dict) is used, it is sorted by key and the key is returned as a list.

Or specify the conditions for sorting:

>>> b = {1:'ab',2:'degg',4:'ght',9:'d'}
>>> sorted(b.items(),key=lambda i:i[0])            #指定按字典里面的键排序
[(1, 'ab'), (2, 'degg'), (4, 'ght'), (9, 'd')]   
>>> 
>>> 
>>> sorted(b.items(),key=lambda i:len(i[1]))       #指定按字典里的value长度排序,默认从小到大
[(9, 'd'), (1, 'ab'), (4, 'ght'), (2, 'degg')]
>>> 
>>> 
>>> sorted(b.items(),key=lambda i:len(i[1]),reverse=True)   #指定按字典里的value长度排序,同时进行翻转,即按value的长度从大到小排列
[(2, 'degg'), (4, 'ght'), (1, 'ab'), (9, 'd')]
Copy after login

The process is: b.iterms() gets the [(key, value)] list of dictionary b. Through the key parameter, the sorting method is specified. Key ([0]) or value ([1]), reverse = True means that it needs to be flipped. The default is from small to large. If it is flipped, it will be from large to small.

For more Python related technical articles, please visit the Python Tutorial column to learn!

The above is the detailed content of What is sorted in python. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
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