[Python-talk] reduction Q

Kent Johnson kent37 at tds.net
Thu Oct 22 13:42:42 EDT 2009


On Thu, Oct 22, 2009 at 11:01 AM,  <bruce.labitt at autoliv.com> wrote:
> There is a generator function that produces as its output 2 arrays, a and
> b.  I'd like to get the average of the ith elements for both arrays.  The
> a and b arrays are the same length, if it matters.
>
> (a,b) = ( myfunc( args ) for f in freqarray )

You have lost me already. What is args? Do you mean the generator
yields a sequence whose elements are pairs of arrays? And you want to
create two new arrays whose values are the average of the values in
the sequence?

( myfunc( args ) for f in freqarray ) is a generator expression, its
value is a generator object, I don't understand how you can assign
that to a tuple.

> can I do something like the following?
>
> (suma,sumb) = reduce(add, (a, b))   # this stops the generator chain...

Again I'm confused. The above is equivalent to
(suma, sumb) = add(a, b)
so it doesn't seem to do what you want.

Assuming that myfunc() takes an element from freqarray and returns two
arrays, and that what you want to do is average the result arrays
separately, and that you have enough memory to hold all the arrays,
then I would do something like this to create two independent lists:
  (alla, allb) = zip(* ( myfunc( f ) for f in freqarray ) )

Then you can sum and average alla and allb separately.

Kent


More information about the Python-talk mailing list