使用函数交换索引切片

Rem*_*man 1 python indexing swap list python-3.x

后续问题: 使用切片的Python交换索引

r = ['1', '2', '3', '4', '5', '6', '7', '8'] 
Run Code Online (Sandbox Code Playgroud)

如果我想交换切片,使用函数,那么正确的方法是什么?

def swap(from,to):
  r[a:b+1], r[c+1:d] = r[c:d], r[a:b]

swap(a:b,c:d)
Run Code Online (Sandbox Code Playgroud)

我想在r中将数字3 + 4与5 + 6 + 7交换:

swap(2:4,4:7)
Run Code Online (Sandbox Code Playgroud)

它是否正确?

B. *_* M. 6

没有任何计算,你可以这样做:

def swap(r,a,b,c,d):
   assert a<=b<=c<=d  
   r[a:d]=r[c:d]+r[b:c]+r[a:b]
Run Code Online (Sandbox Code Playgroud)