Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sort a list of objects based on an attribute of the objects?

I've got a list of Python objects that I'd like to sort by an attribute of the objects themselves. The list looks like:

>>> ut [<Tag: 128>, <Tag: 2008>, <Tag: <>, <Tag: actionscript>, <Tag: addresses>,  <Tag: aes>, <Tag: ajax> ...] 

Each object has a count:

>>> ut[1].count 1L 

I need to sort the list by number of counts descending.

I've seen several methods for this, but I'm looking for best practice in Python.

like image 331
Nick Sergeant Avatar asked Dec 31 '08 16:12

Nick Sergeant


People also ask

How do you sort a list of objects based on an attribute of the objects in Java?

sort() method to sort a list of objects using some examples. By default, the sort() method sorts a given list into ascending order (or natural order). We can use Collections. reverseOrder() method, which returns a Comparator, for reverse sorting.

How do you sort a list by multiple attributes in Python?

A Pythonic solution to in-place sort a list of objects using multiple attributes is to use the list. sort() function. It accepts two optional keyword-only arguments: key and reverse and produces a stable sort.

How do you sort a list of objects in ascending order in Python?

Python List sort() - Sorts Ascending or Descending List. The list. sort() method sorts the elements of a list in ascending or descending order using the default < comparisons operator between items. Use the key parameter to pass the function name to be used for comparison instead of the default < operator.


2 Answers

# To sort the list in place... ut.sort(key=lambda x: x.count, reverse=True)  # To return a new list, use the sorted() built-in function... newlist = sorted(ut, key=lambda x: x.count, reverse=True) 

More on sorting by keys.

like image 149
Kenan Banks Avatar answered Sep 16 '22 15:09

Kenan Banks


A way that can be fastest, especially if your list has a lot of records, is to use operator.attrgetter("count"). However, this might run on an pre-operator version of Python, so it would be nice to have a fallback mechanism. You might want to do the following, then:

try: import operator except ImportError: keyfun= lambda x: x.count # use a lambda if no operator module else: keyfun= operator.attrgetter("count") # use operator since it's faster than lambda  ut.sort(key=keyfun, reverse=True) # sort in-place 
like image 40
tzot Avatar answered Sep 19 '22 15:09

tzot