How to sort multidimensional array by column?

前端 未结 6 1503
不思量自难忘°
不思量自难忘° 2020-12-02 20:00

Is there a way to use the sort() method or any other method to sort a list by column? Lets say I have the list:

[
[John,2],
[Jim,9],
[Jason,1]
]
6条回答
  •  没有蜡笔的小新
    2020-12-02 20:59

    Yes. The sorted built-in accepts a key argument:

    sorted(li,key=lambda x: x[1])
    Out[31]: [['Jason', 1], ['John', 2], ['Jim', 9]]
    

    note that sorted returns a new list. If you want to sort in-place, use the .sort method of your list (which also, conveniently, accepts a key argument).

    or alternatively,

    from operator import itemgetter
    sorted(li,key=itemgetter(1))
    Out[33]: [['Jason', 1], ['John', 2], ['Jim', 9]]
    

    Read more on the python wiki.

提交回复
热议问题