使用函数交换索引切片 [英] Swap slices of indexes using a function
本文介绍了使用函数交换索引切片的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
后续问题:
Python使用切片交换索引
r = ['1', '2', '3', '4', '5', '6', '7', '8']
如果我想要交换切片,使用函数,什么是正确的方法?
If I want to swap slices, using a function, what would be the correct method?
def swap(from,to):
r[a:b+1], r[c+1:d] = r[c:d], r[a:b]
swap(a:b,c:d)
我想将数字3 + 4与5 + 6 + 7换成r:
I want to swap the numbers 3 + 4 with 5 + 6 + 7 in r:
swap(2:4,4:7)
这是正确的吗?
推荐答案
无需任何计算,您可以这样做:
Without any calculation, you can do :
def swap(r,a,b,c,d):
assert a<=b<=c<=d
r[a:d]=r[c:d]+r[b:c]+r[a:b]
这篇关于使用函数交换索引切片的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文