convert loop to list comprehension
Rob Williscroft
rtw at freenet.co.uk
Sat Sep 9 02:12:08 CEST 2006
bvdp at xplornet.com wrote in news:1157758817.446690.105620
@i42g2000cwa.googlegroups.com in comp.lang.python:
> Please help my poor brain :) Every time I try to do a list
> comprehension I find I just don't comprehend ...
>
> Anyway, I have the following bit of code:
>
> seq = [2, 3, 1, 9]
> tmp = []
> for a in range(len(seq)):
> tmp.extend([a]*seq[a])
>
> which correctly returns:
>
> [0, 0, 1, 1, 1, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3]
>
> Question is, can I do this as a list comprehension?
>
Well apparently I can, though it did take me 2 goes:
>>> seq = [2, 3, 1, 9]
>>> sum( [ [a]*seq[a] for a in range(len(seq)) ] )
Traceback (most recent call last):
File "<pyshell#1>", line 1, in -toplevel-
sum( [ [a]*seq[a] for a in range(len(seq)) ] )
TypeError: unsupported operand type(s) for +: 'int' and 'list'
>>> sum( [ [a]*seq[a] for a in range(len(seq)) ], [] )
[0, 0, 1, 1, 1, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3]
>>>
But thats just me showing off what a filthy programmer I am.
My third attempt went like:
>>> [ x for a in a in range(len(seq)) for x in [a] * seq[a] ]
Traceback (most recent call last):
File "<pyshell#3>", line 1, in -toplevel-
[ x for a in a in range(len(seq)) for x in [a] * seq[a] ]
TypeError: iteration over non-sequence
Ah the perils of cut-n-paste (and my what a strange error),
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] ]
[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/
More information about the Python-list
mailing list