I'm trying to sort a list of lists by 1 item that is a float. Problem is, using sort(list, itemgetter(n)) sorts the floats as strings and the output is not what i expect.
list1 = [('1','1',"9999"),('1','1',"9998"),('1','1',"9998.777"),('1','1',"9995111"),('1','1',"110000")]
list2 = sorted(list2, key=itemgetter(2))
print(list2)
actual result:
[('1', '1', '110000'), ('1', '1', '9995111'), ('1', '1', '9998'), ('1', '1', '9998.777'), ('1', '1', '9999')]
Expected result:
[('1', '1', '9998'), ('1', '1', '9998.777'), ('1', '1', '9999'),('1', '1', '110000'),('1', '1', '9995111')]
It sorts them as strings because they are strings. itemgetter
just returns x[2]
, as it is. What you want is a function that takes ax and returns float(x[2])
. So, just use key= lambda x: float(x[2])
If you want to make the float conversion, you can map a function on it:
list2 = list(map(lambda x: (x[0], x[1], float(x[2])), list1))
Then your line list2 = sorted(list1, key=itemgetter(2))
will work as expected.
Otherwise, you can use sorted(list1, key=lambda x: float(x[2]))
as Rakesh mentioned in the comments, to sort by 2nd element casting float type on it.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.