Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - Using Lambda in List.Sort [closed]

I am trying to sort a list of lists based on the 2nd element in the sub list.

Sample Data:

 [[u'm3u33mm534o', 14, 23], [u'2w3dfbv333g', 20, 34], [u'7kv903nfjfr9', 0, 35]]

Sort:

 out.sort(key=lambda x: float(x[1]))

Error:

TypeError: float() argument must be a string or a number

What is the issue here?

like image 366
ExceptionLimeCat Avatar asked Jul 05 '26 18:07

ExceptionLimeCat


1 Answers

Works perfectly for me... Your real list will most probably include an item where the second element is not convertible to a float, eg:

>>> out = [[u'test', None, 35], [u'7kv903nfjfr9', 0, 35], [u'm3u33mm534o', 14, 23], [u'2w3dfbv333g', 20, 34]]
>>> x = out.sort(key=lambda x: float(x[1]))
...
TypeError: float() argument must be a string or a number

To debug, just do something like

for i in out:
    try:
        float(i[1])
    except TypeError:
        print "error is here:", i
like image 175
rainer Avatar answered Jul 07 '26 07:07

rainer