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

前端 未结 10 1692
南笙
南笙 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 08:01

    sorted_by_second = sorted(data, key=lambda tup: tup[1])
    

    or:

    data.sort(key=lambda tup: tup[1])  # sorts in place
    

提交回复
热议问题