Get the App
SLTechnology News&Howtos  ›  Development  › 

How python uses the built-in Sort () method to sort complex iterations

Shulou Source: shulou.com Published: 2022-06-01 05:15:50 11月11日 Update

Editor to share with you how python uses the built-in Sort () method to sort complex iterations. I believe most people don't know much about it, so share this article for your reference. I hope you can learn a lot after reading this article. Let's learn about it together.

Sort complex iterations using the built-in Sort () method

If we need to sort some iterable objects, such as lists, tuples, or dictionaries, we don't need to implement our own sorting algorithm. We can simply use the built-in sorting function. This automatically sorts the numbers in ascending order and returns a new list. If we want the results to be sorted in descending order, we can use the parameter reverse=True. As I said, this applies to any object that can be iterated over, so we can also use tuples here. Note, however, that the result is a list!

Data = (3,5,1,10,9) sortedsorted_data = sorted (data, reverse=True) # [10,9,5,3,1]

Now suppose we have a complex iterator. Here is a list, in which there is a dictionary, and we want to sort the list according to the age in the dictionary. To do this, we can also use the sort function, and then pass in the key parameters that should be used for sorting. The key must be a function, so here we can use lambda and an one-line function that returns the age.

Data = [{"name": "Max", "age": 6}, {"name": "Lisa", "age": 20}, {"name": "Ben", "age": 9}] sortedsorted_data = sorted (data, key=lambda x: X ["age"]) are all the contents of the article "how python uses the built-in Sort () method to sort complex iterations" Thank you for reading! I believe we all have a certain understanding, hope to share the content to help you, if you want to learn more knowledge, welcome to follow the industry information channel!

Tags: Sort iterate complex function method dictionary article content parameter object age result for this not much key ascending order most say number more Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno MySQL Huawei Shulou Tech Info vpn Xiaomi