Sorting a list of objects by attribute
I am trying to sort a list of objects in python, however this code will not work:
import datetime
class Day:
def __init__(self, date, text):
self.date = date
self.text = text
def __cmp__(self, other):
return cmp(self.date, other.date)
mylist = [Day(datetime.date(2009, 01, 02), "Jan 2"), Day(datetime.date(2009, 01, 01), "Jan 1")]
print mylist
print mylist.sort()
The result of this:
[<__main__.Day instance at 0x519e0>, <__main__.Day instance at 0x51a08>]
None
Can anyone show me a good way to solve this? Why does the function sort()
return None
?
0
a source to share
2 answers
mylist.sort () returns nothing, sorts the list in place. Change it to
mylist.sort()
print mylist
to see the correct result.
See http://docs.python.org/library/stdtypes.html#mutable-sequence-types note 7.
The sort () and reverse () methods change the list for space economy when sorting or reversing a large list. Let me remind you that they act as a side effect, they do not return a sorted or inverted list.
+5
a source to share