Cycle a list from alternating sides

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

    cycle between getting items from the forward iter and the reversed one. Just make sure you stop at len(a) with islice.

    from itertools import islice, cycle
    
    iters = cycle((iter(a), reversed(a)))
    b = [next(it) for it in islice(iters, len(a))]
    
    >>> b
    [0, 9, 1, 8, 2, 7, 3, 6, 4, 5]
    

    This can easily be put into a single line but then it becomes much more difficult to read:

    [next(it) for it in islice(cycle((iter(a),reversed(a))),len(a))]
    

    Putting it in one line would also prevent you from using the other half of the iterators if you wanted to:

    >>> iters = cycle((iter(a), reversed(a)))
    >>> [next(it) for it in islice(iters, len(a))]
    [0, 9, 1, 8, 2, 7, 3, 6, 4, 5]
    >>> [next(it) for it in islice(iters, len(a))]
    [5, 4, 6, 3, 7, 2, 8, 1, 9, 0]
    

提交回复
热议问题