Pythonic Swap?

前端 未结 5 557
一整个雨季
一整个雨季 2021-01-08 00:25

I found that i have to perform a swap in python and i write something like this.

arr[first], arr[second] = arr[second], arr[first]

I suppos

5条回答
  •  梦毁少年i
    2021-01-08 00:53

    The one thing I might change in your example code: if you're going to use some long name such as self.memberlist over an over again, it's often more readable to alias ("assign") it to a shorter name first. So for example instead of the long, hard-to-read:

    self.memberlist[someindexA], self.memberlist[someindexB] = self.memberlist[someindexB], self.memberlist[someindexA]
    

    you could code:

    L = self.memberlist
    L[someindexA], L[someindexB] = L[someindexB], L[someindexA]
    

    Remember that Python works by-reference so L refers to exactly the same object as self.memberlist, NOT a copy (by the same token, the assignment is extremely fast no matter how long the list may be, because it's not copied anyway -- it's just one more reference).

    I don't think any further complication is warranted, though of course some fancy ones might easily be conceived, such as (for a, b "normal" indices >=0):

    def slicer(a, b):
      return slice(a, b+cmp(b,a), b-a), slice(b, a+cmp(a,b), a-b)
    
    back, forth = slicer(someindexA, someindexB)
    self.memberlist[back] = self.memberlist[forth]
    

    I think figuring out these kinds of "advanced" uses is a nice conceit, useful mental exercise, and good fun -- I recommend that interested readers, once the general idea is clear, focus on the role of those +cmp and how they make things work for the three possibilities (a>b, a

    Remember, simple is better than complex!

提交回复
热议问题