0

我试图编写一个程序来反转 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
4

1 回答 1

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]
于 2013-10-09T08:49:36.167 回答