'List comprehension with tuples
list_of_tuples = [(2, 4), (3, 3), (4, 2)]
def my_function(list_of_tuples):
best = list_of_tuples[0]
for r in list_of_tuples:
if r[0] * r[1] > best[0] * best[1]:
best = r
return best
I want to write the above function in one line and this is my result
return [i for i in rectangles if i[0] * i[1] > list_of_tuples[0][0] * list_of_tuples[0][1]]
The problem is that I don't know how to write that part with best = r. How can I achieve this?
Solution 1:[1]
Python can help you with this:
def my_function(list_of_tuples):
return max(list_of_tuples, key=lambda k: k[0]*k[1])
Solution 2:[2]
You can use operator.mul() and functools.reduce() to get the product of every element in each tuple, and then you can take the tuple with the maximum product using max().
Tim Roberts's answer is good for when you only have tuples of size two, but this approach can be used for tuples of arbitrary length (the number of elements in each tuple doesn't even have to be the same!):
from operator import mul
from functools import reduce
max(list_of_tuples, key=lambda x: reduce(mul, x))
Even simpler, you can do:
from math import prod
max(list_of_tuples, key=prod)
by a suggestion from Kelly Bundy.
These output:
(3, 3)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Tim Roberts |
| Solution 2 |
