Daniel Chepenko
Daniel Chepenko

Reputation: 2268

How to sort list of two paired elements by their weight?

I'm dealing with such problem:

if __name__ == "__main__":
    data = list(map(int, sys.stdin.read().split()))
    n, capacity = data[0:2]
    elem1 = data[2:(2 * n + 2):2]
    elem2 = data[3:(2 * n + 2):2]
    ziplist = list(zip(values,weights))
    opt_value = get_optimal_value(capacity, elem1, elem2)

So, as I typing

3 40
20 40
50 60
70 80

I got such list

[(20, 40), (50, 60), (70, 80)]

I need to sort my list by the value of "weight", where weight is

elem1/elem2

While testing, I made such list

m = list(x/y for x,y in ziplist)     
[0.5, 0.8333333333333334, 0.875]

And I see that the last element has the best weight, so I need my initial list sorted like this:

[(70, 80), (50, 60), (20, 40)]

I was reading about sorting with key, but I can't understand how to write my proper condition, something like that

 newlist = ziplist.sort(key=lambda m = x/y for x, y in ziplist m)

And moreover, how can I work with my sorted list in order to get elem2 from the first index. So, I have such sorted list:

[(70, 80), (50, 60), (20, 40)]
#code implementation 

a = 70 #output
b = 80 #output

Upvotes: 0

Views: 1522

Answers (1)

zhangyangyu
zhangyangyu

Reputation: 8620

sorted(l, key=lambda elem: elem[0] / elem[1], reverse=True)

Upvotes: 4

Related Questions