convert loop to list comprehension

bvdp at xplornet.com bvdp at xplornet.com
Fri Sep 8 20:28:51 EDT 2006


Rob Williscroft wrote:

<snip>

> But my forth attemp yeilded (If that's a pun I do appologise)
> this:
>
> >>> [ x for a in range(len(seq)) for x in [a] * seq[a] ]

Ahh, that's the magic ... I didn't understand that one could have
multiple "statments" in this single line. Now, you can't have python
line "for a in ... for b in..." can you? I probably shoudn't even try
to figure out how/why it works in a [list].

> [0, 0, 1, 1, 1, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3]
> >>>
>
> Which is possibly something you might of expected.
>
> Note the unrolled version goes:
>
> >>> tmp = []
> >>> for a in range(len(seq)):
>        for x in [a] * seq[a]:
>            tmp.append( x )
>
> >>> tmp
> [0, 0, 1, 1, 1, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3]
> >>>
>
> IOW a comprehension appends rather than extends. Other than
> that you move the value you're appending from the inside of
> the loop('s) to the begining of the comprehension then remove
> newlines and colon's [inside some brakets ofcourse].
>
> Rob.
> --
> http://www.victim-prime.dsl.pipex.com/

Cool ... and damn but you guys are fast with the answers. This appears
to work find, but in a quick and dirty test it appears that the [list]
version takes about 2x as long to run as the original loop. Is this
normal?




More information about the Python-list mailing list