related lists mean value

Chris Rebert clp2 at rebertia.com
Tue Mar 9 00:22:39 CET 2010


On Mon, Mar 8, 2010 at 2:34 PM, dimitri pater - serpia
<dimitri.pater at gmail.com> wrote:
> Hi,
>
> I have two related lists:
> x = [1 ,2, 8, 5, 0, 7]
> y = ['a', 'a', 'b', 'c', 'c', 'c' ]
>
> what I need is a list representing the mean value of 'a', 'b' and 'c'
> while maintaining the number of items (len):
> w = [1.5, 1.5, 8, 4, 4, 4]
>
> I have looked at iter(tools) and next(), but that did not help me. I'm
> a bit stuck here, so your help is appreciated!

from __future__ import division

def group(keys, values):
    #requires None not in keys
    groups = []
    cur_key = None
    cur_vals = None
    for key, val in zip(keys, values):
        if key != cur_key:
            if cur_key is not None:
                groups.append((cur_key, cur_vals))
            cur_vals = [val]
            cur_key = key
        else:
            cur_vals.append(val)
    groups.append((cur_key, cur_vals))
    return groups

def average(lst):
    return sum(lst) / len(lst)

def process(x, y):
    result = []
    for key, vals in group(y, x):
        avg = average(vals)
        for i in xrange(len(vals)):
            result.append(avg)
    return result

x = [1 ,2, 8, 5, 0, 7]
y = ['a', 'a', 'b', 'c', 'c', 'c' ]

print process(x, y)
#=> [1.5, 1.5, 8.0, 4.0, 4.0, 4.0]

It could be tweaked to use itertools.groupby(), but it would probably
be less efficient/clear.

Cheers,
Chris
--
http://blog.rebertia.com



More information about the Python-list mailing list