Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.python > #52141 > unrolled thread
| Started by | Peter Otten <__peter__@web.de> |
|---|---|
| First post | 2013-08-07 18:59 +0200 |
| Last post | 2013-08-07 18:59 +0200 |
| Articles | 1 — 1 participant |
Back to article view | Back to comp.lang.python
This discussion starts older than the indexed window; earlier articles aren't shown. The article labeled Started by
below is the oldest one visible, not the original post.
Re: make elements of a list twice or more. Peter Otten <__peter__@web.de> - 2013-08-07 18:59 +0200
| From | Peter Otten <__peter__@web.de> |
|---|---|
| Date | 2013-08-07 18:59 +0200 |
| Subject | Re: make elements of a list twice or more. |
| Message-ID | <mailman.321.1375894812.1251.python-list@python.org> |
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 top | Article view | comp.lang.python
csiph-web