没有返回语句的python交换函数

问题描述 投票:0回答:2
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 语句?

python return swap
2个回答
1
投票

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']

0
投票

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]
© www.soinside.com 2019 - 2024. All rights reserved.