Cycle a list from alternating sides

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

    You can partition the list into two parts about the middle, reverse the second half and zip the two partitions, like so:

    a = [0,1,2,3,4,5,6,7,8,9]
    mid = len(a)//2
    l = []
    for x, y in zip(a[:mid], a[:mid-1:-1]):
        l.append(x)
        l.append(y)
    # if the length is odd
    if len(a) % 2 == 1:
        l.append(a[mid])
    print(l)
    

    Output:

    [0, 9, 1, 8, 2, 7, 3, 6, 4, 5]
    

提交回复
热议问题