How to sort multidimensional array by column?

前端 未结 6 1478
不思量自难忘°
不思量自难忘° 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:41

    You can use list.sort with its optional key parameter and a lambda expression:

    >>> lst = [
    ...     ['John',2],
    ...     ['Jim',9],
    ...     ['Jason',1]
    ... ]
    >>> lst.sort(key=lambda x:x[1])
    >>> lst
    [['Jason', 1], ['John', 2], ['Jim', 9]]
    >>>
    

    This will sort the list in-place.


    Note that for large lists, it will be faster to use operator.itemgetter instead of a lambda:

    >>> from operator import itemgetter
    >>> lst = [
    ...     ['John',2],
    ...     ['Jim',9],
    ...     ['Jason',1]
    ... ]
    >>> lst.sort(key=itemgetter(1))
    >>> lst
    [['Jason', 1], ['John', 2], ['Jim', 9]]
    >>>
    

提交回复
热议问题