Pythonic Swap?

前端 未结 5 562
一整个雨季
一整个雨季 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条回答
  •  庸人自扰
    2021-01-08 00:31

    It's difficult to imagine how it could be made more elegant: using a hypothetical built-in function ... swap_sequence_elements(arr, first, second) elegant? maybe, but this is in YAGGI territory -- you aren't going to get it ;-) -- and the function call overhead would/should put you off implementing it yourself.

    What you have is much more elegant than the alternative in-line way:

    temp = arr[first]
    arr[first] = arr[second]
    arr[second] = temp
    

    and (bonus!) is faster too (on the not unreasonable assumption that a bytecode ROT_TWO is faster than a LOAD_FAST plus a STORE_FAST).

提交回复
热议问题