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

后端 未结 11 2370
醉酒成梦
醉酒成梦 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:51

    Make sure that you do not have any null or NaN values in the list you want to sort. If there are NaN values, then your sort will be off, impacting the sorting of the non-null values.

    Check out Python: sort function breaks in the presence of nan

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

    multiple criteria can also be implemented through lambda function

    sorted_list = sorted(list_to_sort, key=lambda x: (x[1], x[0]))
    
    0 讨论(0)
  • 2020-11-22 10:55

    More easy to understand (What is Lambda actually doing):

    ls2=[[0,1,'f'],[4,2,'t'],[9,4,'afsd']]
    def thirdItem(ls):
        #return the third item of the list
        return ls[2]
    #Sort according to what the thirdItem function return 
    ls2.sort(key=thirdItem)
    
    0 讨论(0)
  • 2020-11-22 10:56

    Like this:

    import operator
    l = [...]
    sorted_list = sorted(l, key=operator.itemgetter(desired_item_index))
    
    0 讨论(0)
  • 2020-11-22 10:56

    Sorting a Multidimensional Array execute here

    arr=[[2,1],[1,2],[3,5],[4,5],[3,1],[5,2],[3,8],[1,9],[1,3]]
    
    
    
    arr.sort(key=lambda x:x[0])
    la=set([i[0] for i in Points])
    
    for i in la:
        tempres=list()
        for j in arr:
            if j[0]==i:
                tempres.append(j[1])
    
        for j in sorted(tempres,reverse=True):
            print(i,j)
    
    0 讨论(0)
  • 2020-11-22 10:57

    This is a job for itemgetter

    >>> from operator import itemgetter
    >>> L=[[0, 1, 'f'], [4, 2, 't'], [9, 4, 'afsd']]
    >>> sorted(L, key=itemgetter(2))
    [[9, 4, 'afsd'], [0, 1, 'f'], [4, 2, 't']]
    

    It is also possible to use a lambda function here, however the lambda function is slower in this simple case

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