Sort python list by function
Question:
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(???))
Answers:
sort(my_list_of_objects, key=my_number_giving_function)
same for sorted, see the Python Sorting HOWTO
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(???))
sort(my_list_of_objects, key=my_number_giving_function)
same for sorted, see the Python Sorting HOWTO