In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-19 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article will explain in detail how python sorts the parameters in the function. The editor thinks it is very practical, so I share it with you for reference. I hope you can get something after reading this article.
The built-in sorted () function accepts a parameter key to pass a callable object (callable), which returns some values in the object to be sorted, and sorted uses these values to compare objects.
For example, if you have a series of User object instances in your application, and we want to sort them by the user_id property, we can provide a callable object that takes the User instance as input and returns user_id.
Class User: def _ init__ (self, user_id): self.user_id = user_id def _ repr__ (self): return 'User ({})' .format (self.user_id) users = [User (23), User (3), User (99)] print (users) # [User (23), User (3), User (99)] sorted (users, key=lambda u: user_id) # [User (3), User (23) User (99)]
In addition to using lambda expressions, another way is to use operator.attrgetter ()
From operator import attrgettersorted (users, key=attrgetter ('user_id')) # [User (3), User (23), User (99)]
Whether to use lambda expressions or attrgetter () is probably just a personal preference. In general, however, attrgetter () is faster and allows the ability to extract multiple field values at the same time.
This is similar to the use of operator.itemgetter () for dictionaries.
If the User instance also has a first_name and last_name property, you can perform the following sort operation:
By_name = sorted (users, key=attrgetter ('last_name',' first_name'))
Similarly, the techniques used in this section are used for functions such as min () and max ().
Min (Users, key=attrgetter ('user_id')) # User (3) max (Users, key=attrgetter (' user_id')) # User (99) about "how to sort the parameters in a function by python" is the end of this article. I hope the above content can be helpful to you, so that you can learn more knowledge. If you think the article is good, please share it for more people to see.
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.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.