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