Python: Sort a list/tuple/class by specific field

0 Comments

This is something that I have to do every once in a while and can never remember the method. To save myself some time, I've written this here in hope that I can remember it next time.

01.student_tuples = [
02.  ('john', 'A', 15),
03.  ('jane', 'B', 12),
04.  ('dave', 'B', 10),
05.]
06. 
07.# sort by age
08.sorted(student_tuples, key = lambda student: student[2])
09. 
10.[('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)]

This great example is straight from the Python wiki page.

[ Source ]

 
Copyright © Twig's Tech Tips
Theme by BloggerThemes & TopWPThemes Sponsored by iBlogtoBlog