def swapPositions(list, pos1, pos2):
list[pos1], list[pos2] = list[pos2], list[pos1]
return list
seq=['abd','dfs','sdfs','fds','fsd','fsd']
print(swapPositions(seq,2,3))
我们可以不使用 return
语句?
list
对象在python中是一个 可变对象 这意味着它通过引用而不是通过值传递到函数中。所以,你已经在改变 seq
原地踏步,不需要再去做什么。return
语句。
def swapPositions(list, pos1, pos2):
list[pos1], list[pos2] = list[pos2], list[pos1]
seq=['abd','dfs','sdfs','fds','fsd','fsd']
swapPositions(seq,2,3)
print(seq)
# returns ['abd', 'dfs', 'fds', 'sdfs', 'fsd', 'fsd']
Python函数通常遵循两个约定。
None
.你的函数做的是后者,并且应该省去 return
声明。
>>> x = [1, 2, 3, 4]
>>> swapPositions(x, 2, 3)
>>> x
[1, 2, 4, 3]
如果你选择前者。x
就这样吧
def swapPositions(L, pos1, pos2):
L = L.copy()
L[pos1], L[pos2] = L[pos2], L[pos1]
return L
>>> x = [1, 2, 3, 4]
>>> swapPositions(list, 2, 3)
[1, 2, 4, 3]
>>> x
[1, 2, 3, 4]