[Tutor] reduce with comprehension

János Juhász janos.juhasz at VELUX.com
Tue Nov 22 08:19:12 CET 2005


Hi John,

thanks it.

It is great. I looked for it, but I couldn't made it.
I have tried it with wrong order:
# I have tried it so
[x for x in y for y in a]
[[8], [8], [8], [9], [9], [9]] # that is wrong,

# Instead of that you wrote
[x for y in a for x in y]
[[1], [2], [3, 31, 32], [4], [5], [6], [7, 71, 72], [8], [9]]


Yours sincerely,
______________________________
János Juhász


jfouhy at gmail.com wrote on 2005.11.21 23:26:03:

> On 21/11/05, János Juhász <janos.juhasz at velux.com> wrote:
> > I can't imagine how this could be made with list comprehension.
> >
> > >>> import operator
> > >>> a = (([1],[2],[3,31,32],[4]), ([5],[6],[7, 71, 72]), ([8],[9]))
> > >>> reduce(operator.add, a) # it makes a long list now
> > ([1], [2], [3, 31, 32], [4], [5], [6], [7, 71, 72], [8], [9])

> Everything is possible with list comprehensions!

> >>> a = (([1],[2],[3,31,32],[4]), ([5],[6],[7, 71, 72]), ([8],[9]))
> >>> [x for y in a for x in y]
> [[1], [2], [3, 31, 32], [4], [5], [6], [7, 71, 72], [8], [9]]

> We can even go a level deeper!

> >>> [x for z in a for y in z for x in y]
> [1, 2, 3, 31, 32, 4, 5, 6, 7, 71, 72, 8, 9]

> Just make sure your depth is consistent throughout.

> And remember that that single-line expression is hiding nested FOR loops!

> --
> John.



More information about the Tutor mailing list