[pyar] Una manera idiomatica de hacer esto

Ricardo Aráoz ricaraoz en gmail.com
Vie Abr 19 17:39:07 ART 2013


El 19/04/13 11:02, Jairo Trad escribió:
> Paso, con mucha vergüenza, el código que tengo hasta ahora, que esta 
> muy feo, además se morfa el ultimo valor, es decir no anda como 
> debería...
>
> import datetime
>
> promedio = [[datetime.datetime(2013, 4, 10, 12, 0), 
> 23.4],[datetime.datetime(2013, 4, 10, 12, 0), 25.81], 
> [datetime.datetime(2013, 4, 10, 12, 0), 25.08],
> [datetime.datetime(2013, 4, 10, 13, 0), 18.49], 
> [datetime.datetime(2013, 4, 10, 14, 0), 20.74], 
> [datetime.datetime(2013, 4, 10, 14, 0), 25.86] ]
>
> group = []
> new_promedio =  []
> for i in range(len(promedio)-1):
>     if promedio[i][0] == promedio[i+1][0]:
>         group.append(promedio[i])
>     else:
>         group.append(promedio[i])
>         suma = 0
>         for j,k in group:
>             suma += k
>         group[0][1] = suma/len(group)
>         new_promedio.append(group[0])
>         group = []
>
> print new_promedio
>
>
> Saludos, Jairo
>

Qué te parece

 >>> import datetime
 >>> promedio = [[datetime.datetime(2013, 4, 10, 12, 0), 
23.4],[datetime.datetime(2013, 4, 10, 12, 0), 25.81], 
[datetime.datetime(2013, 4, 10, 12, 0), 25.08],
[datetime.datetime(2013, 4, 10, 13, 0), 18.49], [datetime.datetime(2013, 
4, 10, 14, 0), 20.74], [datetime.datetime(2013, 4, 10, 14, 0), 25.86] ]
 >>> fecActual = None
 >>> prom = None
 >>> resumen = []
 >>> for fecha, nro in promedio:
             if not fecActual or fecActual != fecha:
                 if fecActual:
                     resumen.append((fecActual, prom))
                 fecActual = fecha
                 prom = nro
             else:
                 prom = (prom + nro) / 2


 >>> resumen.append((fecActual, prom))
 >>> for fecha, nro in resumen:
             print fecha, nro


2013-04-10 12:00:00 24.8425
2013-04-10 13:00:00 18.49
2013-04-10 14:00:00 23.3
 >>>



More information about the pyar mailing list