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

前端 未结 10 1857
南笙
南笙 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:53

    For sorting by multiple criteria, namely for instance by the second and third elements in a tuple, let

    data = [(1,2,3),(1,2,1),(1,1,4)]
    

    and so define a lambda that returns a tuple that describes priority, for instance

    sorted(data, key=lambda tup: (tup[1],tup[2]) )
    [(1, 1, 4), (1, 2, 1), (1, 2, 3)]
    

提交回复
热议问题