Cycle a list from alternating sides

后端 未结 15 2153
温柔的废话
温柔的废话 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:51

    Use the right toolz.

    from toolz import interleave, take
    
    b = list(take(len(a), interleave((a, reversed(a)))))
    

    First, I tried something similar to Raymond Hettinger's solution with itertools (Python 3).

    from itertools import chain, islice
    
    interleaved = chain.from_iterable(zip(a, reversed(a)))
    b = list(islice(interleaved, len(a)))
    

提交回复
热议问题