为什么在python中交换失败?

时间:2013-10-09 08:47:17

标签: python-3.x

我试图编写一个程序来反转python3中的列表。我第一次尝试:

def reverse(lst):
    """ Reverses lst in place.
    >>> x = [3, 2, 4, 5, 1]
    >>> reverse(x)
    >>> x
    [1, 5, 4, 2, 3]
    """
    n = len(lst)
    for i in range(n//2):
        lst[i], lst[n-i-1] = lst[n-i-1], lst[i]

失败了,我得到的x是原始值。但是,当我将代码更改为此代码时,它起作用了:

def reverse(lst):
    """ Reverses lst in place.
    >>> x = [3, 2, 4, 5, 1]
    >>> reverse(x)
    >>> x
    [1, 5, 4, 2, 3]
    """
    n = len(lst)
    for i in range(n//2):
        temp = lst[i]
        lst[i] = lst[n-i-1]
        lst[n-i-1] = temp

1 个答案:

答案 0 :(得分:2)

按预期工作:

>>> def reverse(lst):
...     n = len(lst)
...     for i in range(n//2):
...         lst[i], lst[n-i-1] = lst[n-i-1], lst[i]
...
>>> lst = [1,2,3,4,5]
>>> reverse(lst)
>>> print(lst)
[5, 4, 3, 2, 1]

顺便说一下,为什么不使用list.reverse

>>> lst = [1,2,3]
>>> lst.reverse()
>>> lst
[3, 2, 1]