jhub1 - 1 year ago 67

Python Question

Ok - been struggling on this for awhile. I've just started learning Python so very new at this.

I have a list of tuples that needs to be sorted by the ratio of the value in each tuple.

Input:

`L = [(1,3), (1,7), (4,8)]`

Returns a sorted list:

`L = [(1,7), (1,3), (4,8)]`

It needs to be sorted using sort and and a custom key. I've seen people use itemgetter and I can't get that version to work either.

My attempt so far:

`sorted(L, key = lambda x: [(i[0]/float(i[1])) for i in x])`

I've been using this as a guide:

How to sort (list/tuple) of lists/tuples?

It seems using itemgetter is the fastest but I can't get that to work either...

Answer Source

You were very close. You didn't need the for loop in your `lambda`

function.

```
>>> L = [(1,3), (1,7), (4,8)]
>>> sorted(L, key=lambda i: i[0]/float(i[1])) # no need for the for loop
[(1, 7), (1, 3), (4, 8)]
>>>
```

You can also make use of `operator.itemgetter()`

like so:

```
>>> L = [(1,3), (1,7), (4,8)]
>>> from operator import itemgetter
>>> ig = itemgetter(0), itemgetter(1)
>>> sorted(L, key= lambda i: ig[0](i)/float(ig[1](i)))
[(1, 7), (1, 3), (4, 8)]
>>>
```