Better way to swap elements in a list?

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

    Here a single list comprehension that does the trick:

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

    The key to understanding it is the following demonstration of how it permutes the list indices:

    In [3]: [i^1 for i in range(10)]
    Out[3]: [1, 0, 3, 2, 5, 4, 7, 6, 9, 8]
    

    The ^ is the exclusive or operator. All that i^1 does is flip the least-significant bit of i, effectively swapping 0 with 1, 2 with 3 and so on.

提交回复
热议问题