How to sort a list/tuple of lists/tuples by the element at a given index?

前端 未结 10 1854
南笙
南笙 2020-11-21 07:09

I have some data either in a list of lists or a list of tuples, like this:

data = [[1,2,3], [4,5,6], [7,8,9]]
data = [(1,2,3), (4,5,6), (7,8,9)]
10条回答
  •  半阙折子戏
    2020-11-21 07:40

    I just want to add to Stephen's answer if you want to sort the array from high to low, another way other than in the comments above is just to add this to the line:

    reverse = True
    

    and the result will be as follows:

    data.sort(key=lambda tup: tup[1], reverse=True)
    

提交回复
热议问题