Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort an array of tuples by product in python

I have an array of 3-tuples and I want to sort them in order of decreasing product of the elements of each tuple in Python. So, for example, given the array

[(3,2,3), (2,2,2), (6,4,1)]

since 3*2*3 = 18, 2*2*2 = 8, 6*4*1 = 24, the final result would be

[(6,4,1), (3,2,3), (2,2,2)]

I know how to sort by, for example, the first element of the tuple, but I'm not sure how to tackle this. Any help would be greatly appreciated. Thanks!

like image 219
user2914093 Avatar asked Oct 24 '13 04:10

user2914093


4 Answers

Use the key argument of sorted/list.sort to specify a function for computing the product, and set the reverse argument to True to make the results descending rather than ascending, e.g.:

from operator import mul
print sorted([(3,2,3), (2,2,2), (6,4,1)], key=lambda tup: reduce(mul, tup), reverse=True)
like image 101
jwodder Avatar answered Oct 19 '22 23:10

jwodder


In [176]: L = [(3,2,3), (2,2,2), (6,4,1)]

In [177]: L.sort(key=lambda (a,b,c):a*b*c, reverse=True)

In [178]: L
Out[178]: [(6, 4, 1), (3, 2, 3), (2, 2, 2)]
like image 45
inspectorG4dget Avatar answered Oct 19 '22 23:10

inspectorG4dget


A simpler solution from my point of view:

a = [(3,2,3), (2,2,2), (6,4,1)]

def f(L):
    return L[0]*L[1]*L[2]

print sorted(a, key = f, reverse = True)

key must be a function that returns a value that will be used in order to sort the list

reverse is True because you want it ordered in decreasing order

like image 42
Christian Tapia Avatar answered Oct 19 '22 23:10

Christian Tapia


>>> from operator import mul
>>> input_list = [(3,2,3), (2,2,2), (6,4,1)]
>>> input_list.sort(key=lambda tup: reduce(mul,tup)) 
>>> print input_list
[(2, 2, 2), (3, 2, 3), (6, 4, 1)]
like image 1
ranendra Avatar answered Oct 19 '22 23:10

ranendra