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


Groups > comp.lang.python > #52140 > unrolled thread

make elements of a list twice or more.

Started byliuerfire Wang <liuerfire@gmail.com>
First post2013-08-07 16:50 +0800
Last post2013-08-21 13:01 -0700
Articles 3 — 3 participants

Back to article view | Back to comp.lang.python


Contents

  make elements of a list twice or more. liuerfire Wang <liuerfire@gmail.com> - 2013-08-07 16:50 +0800
    Re: make elements of a list twice or more. alex23 <wuwei23@gmail.com> - 2013-08-20 13:42 +1000
    Re: make elements of a list twice or more. Tobiah <toby@tobiah.org> - 2013-08-21 13:01 -0700

#52140 — make elements of a list twice or more.

Fromliuerfire Wang <liuerfire@gmail.com>
Date2013-08-07 16:50 +0800
Subjectmake elements of a list twice or more.
Message-ID<mailman.318.1375893821.1251.python-list@python.org>

[Multipart message — attachments visible in raw view] — view raw

Sorry for the title which didn't make clear.

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]?

Thanks.


-- 
Best regards.
/**********************************
google+: +liuerfire <http://gplus.to/onepiece> twitter:
@liuerfire<https://twitter.com/#!/liuerfire>
蛋疼不蛋疼的都可以试着点一下~^_^~ <http://db.tt/YGEdRM0>
***********************************/

[toc] | [next] | [standalone]


#52713

Fromalex23 <wuwei23@gmail.com>
Date2013-08-20 13:42 +1000
Message-ID<kuuoj5$fj$1@dont-email.me>
In reply to#52140
On 7/08/2013 6:50 PM, 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].

from itertools import chain

new_list = list(chain.from_iterable(zip(x,x)))

[toc] | [prev] | [next] | [standalone]


#52788

FromTobiah <toby@tobiah.org>
Date2013-08-21 13:01 -0700
Message-ID<52151C90.9080602@tobiah.org>
In reply to#52140
On 08/07/2013 01:50 AM, liuerfire Wang wrote:
> Sorry for the title which didn't make clear.
> 
> 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].

If you don't care about the order, you can do:

	x = x + x

[toc] | [prev] | [standalone]


Back to top | Article view | comp.lang.python


csiph-web