Better way to swap elements in a list?

后端 未结 14 1251
臣服心动
臣服心动 2020-12-23 13:32

I have a bunch of lists that look like this one:

l = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

I want to swap elements as follows:

fi         


        
相关标签:
14条回答
  • 2020-12-23 14:26

    Another approach with simply re-assigning and slicing technique

    l = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
    for a in range(0,len(l),2):
        l[a:a+2] = l[a-len(l)+1:a-1-len(l):-1]
    print l
    

    output

    [2, 1, 4, 3, 6, 5, 8, 7, 10, 9]
    
    0 讨论(0)
  • 2020-12-23 14:26

    A way using Numpy

    import numpy as np
    
    l = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
    l = np.array(l)
    final_l = list(np.flip(l.reshape(len(l)//2,2), 1).flatten())
    
    0 讨论(0)
提交回复
热议问题