Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort python list by function

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(???)) 
like image 604
vascop Avatar asked Aug 21 '11 01:08

vascop


People also ask

How do you sort a list by function in Python?

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.

How do you sort a list in a function?

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.

What is sort () in Python?

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.

How does sort () sort in Python?

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.


1 Answers

sort(my_list_of_objects, key=my_number_giving_function) 

same for sorted, see the Python Sorting HOWTO

like image 175
msw Avatar answered Sep 30 '22 13:09

msw