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

不带返回语句的python交换函数,python,return,swap,Python,Return,Swap,我们可以在没有返回语句的情况下执行此操作吗?python中的list对象是一个可变对象,这意味着它通过引用而不是值传递到函数中。因此,您已经在适当地更改seq,不需要返回语句 def swapPositions(list, pos1, pos2): list[pos1], list[pos2] = list[pos2], list[pos1] return list seq=['abd','dfs','sdfs','fds','fsd','fsd'] print(swapPos

我们可以在没有返回语句的情况下执行此操作吗?

python中的list对象是一个可变对象,这意味着它通过引用而不是值传递到函数中。因此,您已经在适当地更改
seq
,不需要返回
语句

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))
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
    语句

    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))
    
    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']
    
    如果您选择前者,
    x
    应该不受影响

    >>> x = [1, 2, 3, 4]
    >>> swapPositions(x, 2, 3)
    >>> x
    [1, 2, 4, 3]
    

    对您正在就地修改
    列表
    。这类函数中的Python约定是不返回修改过的对象。@mapf这是生活中最大的谜团之一:我不知道为什么:)我想我必须接受这一点!我想也许有个很好的理由。不过有一个小错误,当您定义
    swapPositions
    时,将
    pos1
    作为参数使用了两次。