Sort a list numerically in Python

前端 未结 4 571
野性不改
野性不改 2021-01-23 03:27

So I have this list, we\'ll call it listA. I\'m trying to get the [3] item in each list e.g. [\'5.01\',\'5.88\',\'2.10\',\'9.45\',\'17.58\',\'2.76\'] in sorted orde

4条回答
  •  滥情空心
    2021-01-23 04:06

    from operator import itemgetter
    lstA.sort(reverse = True, key = itemgetter(3))
    

    And you are good to go. Using itemgetter() within a sort is extremely helpful when you have multiple indexs to sort on. Lets say you wanted to sort alphabetically on the first value in case of a tie you could do the following

    from operator import itemgetter
    lstA.sort(key = itemgetter(0))
    lstA.sort(reverse = True, key = itemgetter(3))
    

    And Voilà!

提交回复
热议问题