Cycle a list from alternating sides

后端 未结 15 2106
温柔的废话
温柔的废话 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:57
    mylist = [0,1,2,3,4,5,6,7,8,9]
    result = []
    
    for i in mylist:
        result += [i, mylist.pop()]
    

    Note:

    Beware: Just like @Tadhg McDonald-Jensen has said (see the comment below) it'll destroy half of original list object.

    0 讨论(0)
  • 2020-12-14 02:00

    Not terribly different from some of the other answers, but it avoids a conditional expression for determining the sign of the index.

    a = range(10)
    b = [a[i // (2*(-1)**(i&1))] for i in a]
    

    i & 1 alternates between 0 and 1. This causes the exponent to alternate between 1 and -1. This causes the index divisor to alternate between 2 and -2, which causes the index to alternate from end to end as i increases. The sequence is a[0], a[-1], a[1], a[-2], a[2], a[-3], etc.

    (I iterate i over a since in this case each value of a is equal to its index. In general, iterate over range(len(a)).)

    0 讨论(0)
  • 2020-12-14 02:01

    Two versions not seen yet:

    b = list(sum(zip(a, a[::-1]), ())[:len(a)])
    

    and

    import itertools as it
    
    b = [a[j] for j in it.accumulate(i*(-1)**i for i in range(len(a)))]
    
    0 讨论(0)
提交回复
热议问题