I have a function that takes an object as an argument and gives me a number. I wish to use this number as the key to sort my list.
If I were to iterate over the list I would do something like:
sorted_list = [] for object in my_list_of_objects: i = my_number_giving_function(object) sorted_list.insert(i, object)
How can I user sorted
to get the same result, and is it advisable? This is what I came up with but I don't know what to put in the '???'
sorted_list = sorted(my_list_of_objects, key=my_number_giving_function(???))
The syntax of the sort() method is: list. sort(key=..., reverse=...) Alternatively, you can also use Python's built-in sorted() function for the same purpose.
There are two ways to sort a list. We can either use the sort() method or the sorted() function. The sort() method is a list method and thus can only be used on lists. The sorted() function works on any iterable.
Python sorted() Function The sorted() function returns a sorted list of the specified iterable object. You can specify ascending or descending order. Strings are sorted alphabetically, and numbers are sorted numerically. Note: You cannot sort a list that contains BOTH string values AND numeric values.
Sorting Numbers The function sorted() did not have to be defined. It's a built-in function that is available in a standard installation of Python. sorted() , with no additional arguments or parameters, is ordering the values in numbers in an ascending order, meaning smallest to largest.
sort(my_list_of_objects, key=my_number_giving_function)
same for sorted, see the Python Sorting HOWTO
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With