How to sort a list of tuples by the alphabetical ordering of one of its elements
I have a list of tuples开发者_StackOverflow, say (name, number, birthday, gender). If I wanted to reverse sort this list by their birthday, how could I sort this in python?
This returns a new object:
>>> import operator
>>> sorted(my_list, key=operator.itemgetter(2), reverse=True)
Or, in-place:
>>> import operator
>>> mylist.sort(key=operator.itemgetter(2), reverse=True)
If you want to sort by two values; assuming tuples are like (name, birthday, time);
>>> mylist.sort(key=operator.itemgetter(1, 2), reverse=True)
精彩评论