Cycle a list from alternating sides

2020-02-08 05:56发布

Given a list

a = [0,1,2,3,4,5,6,7,8,9]

how can I get

b = [0,9,1,8,2,7,3,6,4,5]

That is, produce a new list in which each successive element is alternately taken from the two sides of the original list?

15条回答
ら.Afraid
2楼-- · 2020-02-08 06:27

You can just pop back and forth:

b = [a.pop(-1 if i%2 else 0) for i in range(len(a))]

Note: This destroys the original list, a.

查看更多
姐就是有狂的资本
3楼-- · 2020-02-08 06:27

For fun, here is an itertools variant:

>>> a = [0,1,2,3,4,5,6,7,8,9]
>>> list(chain.from_iterable(izip(islice(a, len(a)//2), reversed(a))))
[0, 9, 1, 8, 2, 7, 3, 6, 4, 5]

This works where len(a) is even. It would need a special code for odd-lengthened input.

Enjoy!

查看更多
ゆ 、 Hurt°
4楼-- · 2020-02-08 06:28

One way to do this for even-sized lists (inspired by this post):

a = range(10)

b = [val for pair in zip(a[:5], a[5:][::-1]) for val in pair]
查看更多
登录 后发表回答