交换不等列表切片的优雅方法?

Jer*_*r J 5 python list python-3.x

我已经研究了在这个网站上的列表中交换元素,但是大多数情况下都涉及将一个元素与另一个元素交换.

在这里,我试图交换不等长度的切片的位置.有关示例列表:

x = [6,2,4,3,4,1,4,5]
Run Code Online (Sandbox Code Playgroud)

我希望用一种优雅的方式来交换列表和变量中的值,例如下面的表格:

x[0:1], x[1:7] = x[1:7], x[0:1]

#Expected output
x = [2, 4, 3, 4, 1, 4, 5, 6]
Run Code Online (Sandbox Code Playgroud)

不出所料,它不起作用,它交换了前两个元素:

#Actual output
x = [2, 6, 4, 3, 4, 1, 4, 5]
Run Code Online (Sandbox Code Playgroud)

又如:交换x[0:4]x[5:7]:

#Expected output
x = [1, 4, 4, 6, 2, 4, 3, 5]
Run Code Online (Sandbox Code Playgroud)

我希望很清楚,交换是这样的,第一个元素slice1占据了第一个元素的前一个位置slice2.其余的如下.

有一种简单的方法可以优雅高效地完成这项工作吗?

Aja*_*234 1

您可以使用collections.deque旋转值:

import collections
x = [6,2,4,3,4,1,4,5]
d = collections.deque(x)
d.rotate(-1)
print(d)
Run Code Online (Sandbox Code Playgroud)

输出:

[2, 4, 3, 4, 1, 4, 5, 6]
Run Code Online (Sandbox Code Playgroud)