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

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

    Stephen's answer is the one I'd use. For completeness, here's the DSU (decorate-sort-undecorate) pattern with list comprehensions:

    decorated = [(tup[1], tup) for tup in data]
    decorated.sort()
    undecorated = [tup for second, tup in decorated]
    

    Or, more tersely:

    [b for a,b in sorted((tup[1], tup) for tup in data)]
    

    As noted in the Python Sorting HowTo, this has been unnecessary since Python 2.4, when key functions became available.

提交回复
热议问题