How to sort a list of lists by a specific index of the inner list?

后端 未结 11 2371
醉酒成梦
醉酒成梦 2020-11-22 10:39

I have a list of lists. For example,

[
[0,1,\'f\'],
[4,2,\'t\'],
[9,4,\'afsd\']
]

If I wanted to sort the outer list by the string field o

相关标签:
11条回答
  • 2020-11-22 10:58

    Itemgetter lets you to sort by multiple criteria / columns:

    sorted_list = sorted(list_to_sort, key=itemgetter(2,0,1))
    
    0 讨论(0)
  • 2020-11-22 11:08
    array.sort(key = lambda x:x[1])
    

    You can easily sort using this snippet, where 1 is the index of the element.

    0 讨论(0)
  • 2020-11-22 11:10

    I think lambda function can solve your problem.

    old_list = [[0,1,'f'], [4,2,'t'],[9,4,'afsd']]
    
    #let's assume we want to sort lists by last value ( old_list[2] )
    new_list = sorted(old_list, key=lambda x: x[2])
    
    #Resulst of new_list will be:
    
    [[9, 4, 'afsd'], [0, 1, 'f'], [4, 2, 't']]
    
    0 讨论(0)
  • 2020-11-22 11:11
    **old_list = [[0,1,'f'], [4,2,'t'],[9,4,'afsd']]
        #let's assume we want to sort lists by last value ( old_list[2] )
        new_list = sorted(old_list, key=lambda x: x[2])**
    

    correct me if i'm wrong but isnt the 'x[2]' calling the 3rd item in the list, not the 3rd item in the nested list? should it be x[2][2]?

    0 讨论(0)
  • 2020-11-22 11:14

    in place

    >>> l = [[0, 1, 'f'], [4, 2, 't'], [9, 4, 'afsd']]
    >>> l.sort(key=lambda x: x[2])
    

    not in place using sorted:

    >>> sorted(l, key=lambda x: x[2])
    
    0 讨论(0)
提交回复
热议问题