user3008918
user3008918

Reputation: 105

Sorting a tuple by its float element

I am trying to sort this tuple by the value of the number, so that it be rearranged in descending order:

l =[('orange', '3.2'), ('apple', '30.2'), ('pear', '4.5')]

as in:

l2 =[('apple', '30.2'), ('pear', '4.5'), ('orange', '3.2')]

I am trying to sort it using this:

l2 = ((k,sorted(l2), key=lambda x: float(x[1]), reverse=True)))
       [value for pair in l2 for value in pair]

But I am getting the error message:

TypeError: float() argument must be a string or a number, not 'tuple'

How can I correct this so that I can indicate that I want to sort by the numbers in each pair? Python syntax still confuses me a lot, because I am very new to it. Any help would be appreciated.

Upvotes: 3

Views: 3846

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1122312

You are muddling up the syntax; you were almost there. This works:

l2 = sorted(l, key=lambda x: float(x[1]), reverse=True)

e.g. call the sorted() function, and pass in the list to sort as the first argument. The other two arguments are keyword arguments (key, and reverse).

Demo:

>>> l = [('orange', '3.2'), ('apple', '30.2'), ('pear', '4.5')]
>>> sorted(l, key=lambda x: float(x[1]), reverse=True)
[('apple', '30.2'), ('pear', '4.5'), ('orange', '3.2')]

You can also sort the list in-place:

l.sort(key=lambda x: float(x[1]), reverse=True)

with the same two keyword arguments.

Upvotes: 12

Related Questions