[Tutor] Alternative to nested loops

Karl Pflästerer khp at pflaesterer.de
Sun Mar 19 23:11:12 CET 2006


On 19 Mrz 2006, sanelson at gmail.com wrote:

> I had a feeling I could do this:
>
>>>> foo
> [[1, 2, 3], [1, 2, 3], [1, 2, 3]]
>>>> for c in foo:
> ...     for b in c:
> ...             print b
> ...
> 1
> 2
> 3
> 1
> 2
> 3
> 1
> 2
> 3
>
> Using a list comprehension, as it seemed to me like I was saying: b

I wouldn't use a list comprehension here since you don't use the list
returned.  A list comprehension is used if you need a list not to
iterate over a list and e.g print the elemenst.

> for c in foo, but I can't see how to do this.  Ultimately I want to
> sum each number and produce a total.  I know how to do this as above,
> but was wondering if there is an alternative / better way?

Use e.g. reduce:

.>>> reduce(lambda s, L: s + sum(L), foo, 0)
.18



   Karl
-- 
Please do *not* send copies of replies to me.
I read the list


More information about the Tutor mailing list