May I use groupby to solve this case in python?
Question: I have a redis database that it's receiving data from Arduino every ten
seconds.

Now, I want to make six ten-second data calculate one sixty-second data and
then get avg, max, min of six ten-second data as follow.

    
    
    import json
    
    a = [u'{"id":"proximity_sensor1","tstamp":1440643570238,"avg":15.0,"coefVariation":0.0,"anom":0,"max":15.0,"min":15.0,"sample_size":10}',
     u'{"id":"proximity_sensor1","tstamp":1440643580307,"avg":15.0,"coefVariation":0.0,"anom":0,"max":15.0,"min":15.0,"sample_size":9}',
     u'{"id":"proximity_sensor1","tstamp":1440643590242,"avg":15.0,"coefVariation":0.0,"anom":0,"max":15.0,"min":15.0,"sample_size":9}',
     u'{"id":"proximity_sensor1","tstamp":1440643590242,"avg":15.0,"coefVariation":0.0,"anom":0,"max":15.0,"min":15.0,"sample_size":8}',
     u'{"id":"proximity_sensor1","tstamp":1440643590242,"avg":15.0,"coefVariation":0.0,"anom":0,"max":15.0,"min":15.0,"sample_size":9}',
     u'{"id":"proximity_sensor1","tstamp":1440643590242,"avg":15.0,"coefVariation":0.0,"anom":0,"max":15.0,"min":15.0,"sample_size":9}']
    
    a = map(lambda x: json.loads(x), a)
    
    #print a
    
    def abc(aaa):
        for index in range(0, len(aaa), 6):
            abc = aaa[index:(index+6)]
            tuples = [('avg', 'max', 'min')]
            avg = sum(map(lambda x: x['avg'], abc))/6
            min_ = min(map(lambda x: x['min'], abc))
            max_ = max(map(lambda x: x['max'], abc))
            yield [avg, max_, min_]
    
    print list(abc(a))
    

I am thinking whether it has better method to solve or not. If I use
`itertools.groupby`, may I solve it faster? or anyone has good idea to
simplify calculated process?


Answer: Normally itertools.groupby is used with some condition to group the elements ,
but since in your case you are not having any such conditions , instead you
just want to group every 6 elements together, I don't think using
itertools.groupby would give any benefit.

That being said there are some other improvements I can suggest -

  1. You can use the 'key' argument for max/min functions rather than your current method of map/lambda , Example - 
    
        max_ = max(abc, key= lambda x:x['max'])['max']
    

Similarly for min() function.

  2. Also , I think it would be more readable to have a list comprehension for sum() , rather than map/lambda . Example -
    
         avg = sum([x['avg'] for x in abc])/6
    

