convert loop to list comprehension
bvdp at xplornet.com
bvdp at xplornet.com
Fri Sep 8 20:37:02 EDT 2006
bearophileHUGS at lycos.com wrote:
> Two possibile solutions:
>
> seq = [2, 3, 1, 9]
>
> print sum( ([i]*n for i,n in enumerate(seq)), [])
>
> print [i for i, x in enumerate(seq) for _ in xrange(x)]
>
Cool as well. So much to learn :)
1. Using an _ is an interesting way to use a throw-away variable. Never
would I think of that ... but, then, I don't do Perl either :)
2. Any reason for xrange() instead of range()
> The second one is probably quite faster.
This seems to be a bit faster than the other suggestion, but is still
quite a bit slower than the original loop. Guess that I'll stick with
the loop for now.
Thanks again!
More information about the Python-list
mailing list