Swap slices of indexes using a function

大兔子大兔子 提交于 2019-11-30 09:53:56

问题


Follow-up question of: Python swap indexes using slices

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)

I want to swap the numbers 3 + 4 with 5 + 6 + 7 in r:

swap(2:4,4:7)

Is this correct?


回答1:


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]



回答2:


An interesting (but silly one, the one by B. M. is clearly better) solution would be to create an object that supports slicing:

class _Swapper(object):
    def __init__(self, li):
        self.list = li

    def __getitem__(self, item):
        x = list(item)
        assert len(x) == 2 and all(isinstance(i) for i in x)
        self.list[x[0]], self.list[x[1]] = self.list[x[1]], self.list[x[0]]

def swap(li):
    return _Swapper(li)

swap(r)[a:b, c:d]


来源:https://stackoverflow.com/questions/36953810/swap-slices-of-indexes-using-a-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!