On 8 Ott, 22:23, beginner <[EMAIL PROTECTED]> wrote:
> Hi All,
>
> I have a list of records like below:
>
> rec=[{"F1":1, "F2":2}, {"F1":3, "F2":4} ]
>
> Now I want to write code to find out the ratio of the sums of the two
> fields.
>
> One thing I can do is:
>
> sum(r["F1"] for r in rec)/sum(r["F2"] for r in rec)
>
> But this is slow because I have to iterate through the list twice.
> Also, in the case where rec is an iterator, it does not work.
>
> I can also do this:
>
> sum1, sum2= reduce(lambda x, y: (x[0]+y[0], x[1]+y[1]), ((r["F1"],
> r["F2"]) for r in rec))
> sum1/sum2
>
> This loops through the list only once, and is probably more efficient,
> but it is less readable.
>
> I can of course use an old-fashioned loop. This is more readable, but
> also more verbose.
>
> What is the best way, I wonder?
>
> -a new python programmerThe loop way is probably the right choice. OTHA, you could try to make more readable the 'reduce' approach, writing it like this: def add_r( sums, r ): return sums[0]+r['F1'], sums[1]+r['F2'] sum_f1, sum_f2 = reduce( add_r, rec, (0,0) ) result = sum_f1/sum_f2 Less verbose than the for loop, but IMO almost as understandable : one only needs to know the semantic of 'reduce' (which for a python programmer is not big thing) and most important the code does only one thing per line. Ciao ----- FB -- http://mail.python.org/mailman/listinfo/python-list
