Python/Sorting: Difference between revisions
From charlesreid1
No edit summary |
No edit summary |
||
| Line 24: | Line 24: | ||
['jane', 'dave', 'john'] | ['jane', 'dave', 'john'] | ||
</pre> | </pre> | ||
[[Category:Python]] | |||
[[Category:Programming]] | |||
[[Category:Sorting]] | |||
Latest revision as of 00:07, 28 March 2017
Python sorting: https://wiki.python.org/moin/HowTo/Sorting
Python sorted containers: http://www.grantjenks.com/docs/sortedcontainers/
Python bintrees implementation of dictionaries and lists: https://pypi.python.org/pypi/bintrees
>>> Student.__eq__ = lambda self, other: self.age == other.age
>>> Student.__ne__ = lambda self, other: self.age != other.age
>>> Student.__lt__ = lambda self, other: self.age < other.age
>>> Student.__le__ = lambda self, other: self.age <= other.age
>>> Student.__gt__ = lambda self, other: self.age > other.age
>>> Student.__ge__ = lambda self, other: self.age >= other.age
>>> sorted(student_objects)
[('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)]
Another cool example: the keys we use to sort do not have to be part of the objects themselves, we can pass in a dictionary with labels and keys.
>>> students = ['dave', 'john', 'jane']
>>> newgrades = {'john': 'F', 'jane':'A', 'dave': 'C'}
>>> sorted(students, key=newgrades.__getitem__)
['jane', 'dave', 'john']