Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

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

2025-02-23 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

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!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report