我必须在 Python 中反转列表,我知道 reverse() 方法可以很好地完成这项工作。 然而,我偶然发现了这段也能完成这项工作的代码,但我无法完全理解它。
这是返回列表的函数。
def reverse(list):
for i in range(len(list) // 2):
list[i], list[len(list) -i -1] = list[len(list) -i -1], list[i]
return list
为什么循环在这里经过列表长度的一半?而且,我不明白第三行的两个逗号。
请您参考如下方法:
def reverse(list):
for i in range(len(list) // 2):
print('Swapping {} and {}'.format(i, len(list) -i -1))
# list[i], list[len(list) -i -1] = list[len(list) -i -1], list[i]
return list
reverse(range(9))
产量
Swapping 0 and 8
Swapping 1 and 7
Swapping 2 and 6
Swapping 3 and 5
这应该让您了解代码的作用。
这有助于了解这一点
a, b = b, a
交换变量 a 和 b 中的值。在作业中 Python evaluates the right-hand side of the assignment first .然后将值分配给左侧的变量。
所以
list[i], list[len(list) -i -1] = list[len(list) -i -1], list[i]
正在交换列表中 i 和 len(list)-i-1 索引位置中的值。
顺便说一句,将变量命名为 list 是不好的,因为它会隐藏同名的 Python 内置函数。
