make elements of a list twice or more.
Peter Otten
__peter__ at web.de
Wed Aug 7 12:59:55 EDT 2013
liuerfire Wang wrote:
> Here is a list x = [b, a, c] (a, b, c are elements of x. Each of them are
> different type). Now I wanna generate a new list as [b, b, a, a, c, c].
>
> I know we can do like that:
>
> tmp = []
> for i in x:
> tmp.append(i)
> tmp.append(i)
>
> However, I wander is there a more beautiful way to do it, like [i for i in
> x]?
Using itertools:
>>> items
[b, a, c]
>>> from itertools import chain, tee, repeat
>>> list(chain.from_iterable(zip(*tee(items))))
[b, b, a, a, c, c]
Also using itertools:
>>> list(chain.from_iterable(repeat(item, 2) for item in items))
[b, b, a, a, c, c]
For lists only, should be fast:
>>> result = 2*len(items)*[None]
>>> result[::2] = result[1::2] = items
>>> result
[b, b, a, a, c, c]
But I would call none of these beautiful...
More information about the Python-list
mailing list