[Tutor] Re: Can you modify every nth item in a list with a single assignment?
Andrei
project5@redrival.net
Sat Jun 14 08:57:01 2003
Alan Gauld wrote:
>> >>> b = [1, 2, 3, 4, 5, 6, 7, 8, 9]
>> >>> [ item in range(2, len(b), 3) and 2*b[item] or b[item] for item
> in
>>range(0, len(b))]
>
> Very clever, but it is still two lines and much more
One line, but wrapped in an unfortunate manner by Mozilla.
> complicated than the explicit loop version:
>
> b = [1, 2, 3, 4, 5, 6, 7, 8, 9]
> for n in range(2,len(b),3): b[n] *= 2
>
> Alan G.
Duh, so obvious and I didn't see it (I always start a new line after
":"). On the other hand, the list comprehension could be used to change
different items in different ways (e.g. every third item times 2, the
other ones plus 2) in a single, extremely long and unmaintainable line.
I liked Alfred Milgrom's solution too.
Andrei
=====
Mail address in header catches spam. Real contact info (decode with rot13):
cebwrpg5@bcrenznvy.pbz. Fcnz-serr! Cyrnfr qb abg hfr va choyvp cbfgf. V
ernq gur yvfg, fb gurer'f ab arrq gb PP.