The python tutorial sorts parameters in a function

  • 2021-12-04 19:12:02
  • OfStack

The built-in sorted () function accepts a parameter key to pass a callable object (callable) that returns some values from the object to be sorted, and sorted uses these values to compare objects.

For example, if there are 1 series of User object instances in an application and we want to sort them by the user_id attribute, 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 the lambda expression, another way is to use operator. attrgetter ()


from operator import attrgetter
sorted(users, key=attrgetter('user_id'))
# [User(3), User(23), User(99)]

Whether to use the lambda expression or attrgetter () is probably just a personal preference. In general, however, attrgetter () is a little 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 1 first_name and last_name attribute, you can perform the following sort operation:

by_name = sorted(users, key=attrgetter('last_name', 'first_name'))

Similarly, the techniques used in this section apply to functions like min () and max ().


min(Users, key=attrgetter('user_id'))
# User(3)
max(Users, key=attrgetter('user_id'))
# User(99)

The above is the python tutorial on the function of the parameters of the details of sorting, more about the Python parameters of sorting information please pay attention to other related articles on this site!


Related articles: