Sort a list numerically in Python

前端 未结 4 616
野性不改
野性不改 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:04

    If you want to return the complete list in sorted order, this may work. This takes your input list and runs sorted on top of it. The reverse argument set to True sorts the list in reverse (descending) order, and the key argument specifies the method by which to sort, which in this case is the float of the third argument of each list:

    In [5]: l = [['John Doe', u'25.78', u'20.77', '5.01'] # continues...    
    In [6]: sorted(l, reverse=True, key=lambda x: float(x[3]))
    Out[6]:
    [['Santa', u'31.13', u'13.55', '17.58'],
     ['Michael Jordan', u'28.50', u'19.05', '9.45'],
     ['Jane Doe', u'21.08', u'15.20', '5.88'],
     ['John Doe', u'25.78', u'20.77', '5.01'],
     ['Easter Bunny', u'17.20', u'14.44', '2.76'],
     ['James Bond', u'20.57', u'18.47', '2.10']]
    

    If you only need the values in sorted order, the other answers provide viable ways of doing so.

提交回复
热议问题