How to use the quick sort to sort by index in a list of a list

后端 未结 1 1204
借酒劲吻你
借酒劲吻你 2021-01-24 04:26

I am trying to use a quick sort to sort through a list of lists at index [1]. For example:

list = [[2, 5, 3],
        [2, 4, 9],
        [0, 9, 1],
        [1, 1         


        
相关标签:
1条回答
  • 2021-01-24 05:14

    You want to use the key argument in list.sort:

    import operator
    mylist = [[2, 5, 3],
              [2, 4, 9],
              [0, 9, 1],
              [1, 1, 1],
              [4, 7, 5]]
    
    mylist.sort(key=operator.itemgetter(1))
    

    Output:

    >>> mylist = [[2, 5, 3],
    ...           [2, 4, 9],
    ...           [0, 9, 1],
    ...           [1, 1, 1],
    ...           [4, 7, 5]]
    >>> 
    >>> mylist.sort(key=operator.itemgetter(1))
    >>> mylist
    [[1, 1, 1], [2, 4, 9], [2, 5, 3], [4, 7, 5], [0, 9, 1]]
    
    0 讨论(0)
提交回复
热议问题