Tago
Tago

Reputation: 11

How to sort a list of lists by an item of the sublist that is a float

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')]

Upvotes: 0

Views: 169

Answers (2)

pissall
pissall

Reputation: 7399

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.

Upvotes: 0

blue note
blue note

Reputation: 29081

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 a x and returns float(x[2]). So, just use key= lambda x: float(x[2])

Upvotes: 2

Related Questions