Method to sort a list of lists?

后端 未结 3 1987
囚心锁ツ
囚心锁ツ 2020-12-06 12:08

I have a list of lists (can\'t be tuples since I have to generate it dynamically) and it is structured as a list of lists of one int and one float Like so:

[         


        
相关标签:
3条回答
  • 2020-12-06 12:33

    How about using they key parameter of sorted...

    sorted_list = sorted([[1,1.0345],[3,4.89],[2,5.098],[2,5.97]], key=lambda x: x[1])
    

    This tells python to sort the list of lists using the item at index 1 of each list as the key for the compare.

    0 讨论(0)
  • 2020-12-06 12:45
    >>> l = [[1,1.0345],[2,5.098],[3,4.89],[2,5.97]]
    >>> l.sort(key=lambda x: x[1])
    >>> l
    [[1, 1.0345], [3, 4.8899999999999997], [2, 5.0979999999999999], [2, 5.9699999999999998]]
    
    0 讨论(0)
  • 2020-12-06 12:50

    Pass the key argument.

    L.sort(key=operator.itemgetter(1))
    
    0 讨论(0)
提交回复
热议问题