Better way to swap elements in a list?

后端 未结 14 1323
臣服心动
臣服心动 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:13

    I don't see anything wrong with your implementation at all. But you could perhaps do a simple swap instead.

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

    EDIT Apparently, Python has a nicer way to do a swap which would make the code like this

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

提交回复
热议问题