Let's say I have a list:
lista = [(1,1), (1,2), (1,3), (2,6), (2,4), (3,1), (3,2)]
And I want to know the maximum and minimum values of the second element, grouped by the first. That is:
{ 1:(1,3), 2:(4,6), 3:(1,2) }
I thought about using an understanding along with groupby
function:
{
a:(min(x[1] for x in b), max(x[1] for x in b))
for a,b in groupby(sorted(lista), lambda x: x[0])
}
The problem is that the first use of b
consumes all elements of the iterator, so the second use finds the iterator empty:
ValueError: max () arg is an empty sequence
I thought about creating a list with the iterator, or maybe using tee
, but I do not know how to fit it into understanding without having to undo it completely and turn it into a loop. It is possible? How to do?