Cycle a list from alternating sides

后端 未结 15 2093
温柔的废话
温柔的废话 2020-12-14 01:03

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 lis

15条回答
  •  温柔的废话
    2020-12-14 01:47

    Not at all elegant, but it is a clumsy one-liner:

    a = range(10)
    [val for pair in zip(a[:len(a)//2],a[-1:(len(a)//2-1):-1]) for val in pair]
    

    Note that it assumes you are doing this for a list of even length. If that breaks, then this breaks (it drops the middle term). Note that I got some of the idea from here.

提交回复
热议问题