Get the App
SLTechnology News&Howtos  ›  Internet Technology  › 

What is the function of the sorted () function in Python

Shulou Source: shulou.com Published: 2022-06-02 07:11:21 09月30日 Update

What is the function of the sorted () function in Python? I believe many inexperienced people don't know what to do about it. Therefore, this paper summarizes the causes and solutions of the problem. Through this article, I hope you can solve this problem.

Description

The sorted () function sorts all iterating objects.

The difference between sort and sorted:

Sort is a method applied to list, and sorted can sort all iterable objects.

List's sort method returns an operation on an existing list with no return value, while the built-in function sorted method returns a new list, not an operation based on the original.

Grammar

Sorted syntax:

Sorted (iterable, cmp=None, key=None, reverse=False)

Parameter description:

Iterable-iterable object.

Cmp-comparison function, which has two parameters, both of which are taken from the iterable object. The rule that this function must follow is: return 1 if greater than 1, return-1 if less than, and return 0 if equal to.

Key-elements that are mainly used for comparison, with only one parameter, the specific parameter of the function is taken from the iterable object, specifying an element in the iterable object to sort.

Reverse-collation, reverse = True descending, reverse = False ascending (default).

Return value

Returns the reordered list.

Example

The following example shows how to use sorted:

> > a = [5, sorted (a) # keep the original list > > a] > > b [5, 7, 3, 4, 5, 6, 7] > L = [('baked pencils 2), (' aura pencils 1), ('cedars dudes 3)] > sorted (L) (L, cmp=lambda XJI) CPM (x [1]) Y [1])) # using cmp functions [('aqure, 1), (' breadth, 2), ('canals, 3), (' dudes, 4)] > sorted (L, key=lambda x key=lambda x [1]) # using key [('aura, 1), (' breadth, 2), ('canals, 3), (' dudes, 4)] > > students = [('john',' Aids, 15) ('jane',' bones, 12), ('dave',' bands, 10)] > sorted (students, key=lambda s: s [2]) # sorted by age [('dave',' bones, 10), ('jane',' bands, 12), ('john',' Aids, 15)] > > sorted (students, key=lambda 's: s [2], reverse=True) # in descending order [('john',' A') 15), ('jane',' Bond, 12), ('dave',' Bamboo, 10)] > finish reading the above Have you mastered the function of the sorted () function in Python? If you want to learn more skills or want to know more about it, you are welcome to follow the industry information channel, thank you for reading!

Tags: Functions objects methods sorting iterations parameters actions elements content instances more rules syntax problems helpless for this two use methods ascending order reasons Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno macOS Linux MariaDB Xiaomi NVidia