How to use an iterator twice within an understanding?

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:

{ 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?

    
asked by anonymous 19.03.2015 / 21:05

2 answers

0

I found two forms, one using lambda (which only works for the key or pro value, but not both):

>>> {
...   a:(lambda b: (min(x[1] for x in b), max(x[1] for x in b)))(list(b))
...   for a,b in groupby(sorted(lista), lambda x: x[0])
... }
{1: (1, 3), 2: (4, 6), 3: (1, 2)}

Other using another for within understanding:

>>> {
...   a:(min(x[1] for x in c), max(x[1] for x in c))
...   for a,b in groupby(sorted(lista), lambda x: x[0])
...   for c in [list(b)]
... }
{1: (1, 3), 2: (4, 6), 3: (1, 2)}
    
19.03.2015 / 23:15
0

"" " Simple is better than complex. "" "

mylist = [(1,1), (1,2), (1,3), (2,6), (2,4), (3,1), (3,2)]
group = {}
for key, val in mylist:
    group[key] = (min(group[key][0], val), max(group[key][1], val)) if key in group else (val, val)

And in this case, "simple" greatly reduces the apparent complexity of what you want to do (there is no need to sort or groupby) ...

It is done in three lines, because the focus with lists comprehensions and the like is not to diminish readability- it is to have a practical and shorter way of writing simple operations to an element vector - in particular operations involving mapping and filtering . If you start getting too complex, always remember that "Readability counts."

    
20.03.2015 / 16:54