不带返回语句的python交换函数

2024-05-09 20:57:33 发布

您现在位置:Python中文网/ 问答频道 /正文

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语句的情况下做到这一点吗


Tags: returndef情况语句seqlistprintdfs
2条回答

python中的list对象是一个可变对象,这意味着它通过引用而不是通过值传递到函数中。因此,您已经在适当地更改了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函数通常遵循两种约定:

  1. 返回一个新的对象,保持参数不变
  2. 就地修改参数,并返回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]

相关问题 更多 >