How to sort multidimensional array by column?

前端 未结 6 1414
不思量自难忘°
不思量自难忘° 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]]
    >>>
    
    0 讨论(0)
  • 2020-12-02 20:43
    sorted(list, key=lambda x: x[1])
    

    Note: this works on time variable too.

    0 讨论(0)
  • 2020-12-02 20:44

    below solution worked for me in case of required number is float. Solution:

    table=sorted(table,key=lambda x: float(x[5]))
    for row in table[:]:
        Ntable.add_row(row)
    

    '

    0 讨论(0)
  • 2020-12-02 20:49

    You can use the sorted method with a key.

    sorted(a, key=lambda x : x[1])
    
    0 讨论(0)
  • 2020-12-02 20:54

    The optional key parameter to sort/sorted is a function. The function is called for each item and the return values determine the ordering of the sort

    >>> lst = [['John', 2], ['Jim', 9], ['Jason', 1]]
    >>> def my_key_func(item):
    ...     print("The key for {} is {}".format(item, item[1]))
    ...     return item[1]
    ... 
    >>> sorted(lst, key=my_key_func)
    The key for ['John', 2] is 2
    The key for ['Jim', 9] is 9
    The key for ['Jason', 1] is 1
    [['Jason', 1], ['John', 2], ['Jim', 9]]
    

    taking the print out of the function leaves

    >>> def my_key_func(item):
    ...     return item[1]
    

    This function is simple enough to write "inline" as a lambda function

    >>> sorted(lst, key=lambda item: item[1])
    [['Jason', 1], ['John', 2], ['Jim', 9]]
    
    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题