Custom Search

Wednesday, February 27, 2013

How To Python Sorting List of Tuples

student_tuples = [
        ('john', 'A', 15),
        ('jane', 'B', 12),
        ('dave', 'B', 10),
    ]

sorted(student_tuples, key=lambda student: student[2]) ### sort by age
* "key" parameter to specify a function to be called on each list element prior to making comparisons.

sorted(student_tuples, key=lambda student: student[2], reverse=True)

import operator
sorted(student_tuples, key=operator.itemgetter(2))

No comments:

Post a Comment