Cycle a list from alternating sides

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

    A very nice one-liner in Python 2.7:

    results = list(sum(zip(a, reversed(a))[:len(a)/2], ()))
    >>>> [0, 9, 1, 8, 2, 7, 3, 6, 4, 5]
    

    First you zip the list with its reverse, take half that list, sum the tuples to form one tuple, and then convert to list.

    In Python 3, zip returns a generator, so you have have to use islice from itertools:

    from itertools import islice
    results = list(sum(islice(zip(a, reversed(a)),0,int(len(a)/2)),()))
    

    Edit: It appears this only works perfectly for even-list lengths - odd-list lengths will omit the middle element :( A small correction for int(len(a)/2) to int(len(a)/2) + 1 will give you a duplicate middle value, so be warned.

提交回复
热议问题