开发者

How to sort a list of tuples by the alphabetical ordering of one of its elements

开发者 https://www.devze.com 2023-03-24 03:25 出处:网络
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:

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)
0

精彩评论

暂无评论...
验证码 换一张
取 消