Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #52141

Re: make elements of a list twice or more.

From Peter Otten <__peter__@web.de>
Subject Re: make elements of a list twice or more.
Date 2013-08-07 18:59 +0200
Organization None
References <CAFysF+Sh=1_K9++GELiGjYe8t-T53m0_6H=5FZyL8XEer8t8XA@mail.gmail.com>
Newsgroups comp.lang.python
Message-ID <mailman.321.1375894812.1251.python-list@python.org> (permalink)

Show all headers | View raw


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...

Back to comp.lang.python | Previous | Next | Find similar | Unroll thread


Thread

Re: make elements of a list twice or more. Peter Otten <__peter__@web.de> - 2013-08-07 18:59 +0200

csiph-web