how to duplicate array entries

Peter Otten __peter__ at web.de
Mon Jan 11 03:57:30 EST 2010


Alf P. Steinbach wrote:

> Re the thing I don't understand: it's the same in C++, people using hours
> on figuring out how to do something very simple in an ungrokkable indirect
> and "compiled" way using template metaprogramming stuff, when they could
> just write a simple 'for' loop and be done with in, say, 3 seconds, and
> much clearer too!

Most of that stuff doesn't end in code meant to do anything important. It's 
more like gymnastics that helps you keep your mind in shape. 
Or so I would hope.

>>> items = [1, 2, 3]
>>> result = 3*len(items)*[None]
>>> result[::3] = result[1::3] = result[2::3] = items
>>> result
[1, 1, 1, 2, 2, 2, 3, 3, 3]

>>> from itertools import *
>>> list(chain.from_iterable(starmap(repeat, izip(items, repeat(3)))))
[1, 1, 1, 2, 2, 2, 3, 3, 3]

;)

Peter



More information about the Python-list mailing list