Better way to swap elements in a list?

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

    One of the possible answer using chain and list comprehension

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

提交回复
热议问题