Reversing a list using slice notation

后端 未结 8 1909
忘掉有多难
忘掉有多难 2020-11-28 22:49

in the following example:

foo = [\'red\', \'white\', \'blue\', 1, 2, 3]

where: foo[0:6:1] will print all elements in foo. Howe

8条回答
  •  攒了一身酷
    2020-11-28 23:21

    Complement. to reverse step by 2:

    A = [1,2,2,3,3]
    n = len(A)
    res = [None] * n
    mid = n//2 + 1 if n%2 == 1 else n//2
    
    res[0::2] = A[0:mid][::-1]
    res[1::2] = A[0:mid][::-1]
    print(res)
    

    [2, 3, 2, 3, 1]

提交回复
热议问题