2
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 to say:
{ 1:(1,3), 2:(4,6), 3:(1,2) }
I thought I’d use an understanding along with function groupby
:
{
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 to create a list with the iterator, or maybe use the function tee
, but I don’t know how to fit that into understanding without having to completely undo it and turn it into a loop. Is that possible? How to do?
I disagree that a declarative form is less readable than an imperative. I know this second one is more understandable for beginner programmers ("lowest common denominator"), but those who already have some experience in functional programming should not have much difficulty understanding the first one, at least no more than the second one (for example, see that code snippet of a system I’m developing, do you have any difficulty understanding what it’s doing? And the loops that I would need to do if I couldn’t use understandings, would it be more readable?).
– mgibsonbr
Anyway, I accept the criticism and thank you for the alternative suggestion. However, this was just an example (doubt that arose when trying to answer another question), I was interested in a generic response to this problem (using the same iterator twice without consuming it, and not being able to use an auxiliary variable), and this does not answer what was asked.
– mgibsonbr