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!
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)
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)]
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
>>> 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)]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With