Skip to main content
 首页 » 编程设计

python之使用函数交换索引切片

2025年05月04日16thcjp

后续问题: Python swap indexes using slices

r = ['1', '2', '3', '4', '5', '6', '7', '8']  

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

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

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

swap(2:4,4:7) 

这是正确的吗?

请您参考如下方法:

无需任何计算,您可以:

def swap(r,a,b,c,d): 
   assert a<=b<=c<=d   
   r[a:d]=r[c:d]+r[b:c]+r[a:b]