反转列表中的项目

use*_*170 1 python

我必须在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
Run Code Online (Sandbox Code Playgroud)

为什么循环遍历列表长度的一半?而且,我不理解第三行中的两个逗号.

unu*_*tbu 6

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))
Run Code Online (Sandbox Code Playgroud)

产量

Swapping 0 and 8
Swapping 1 and 7
Swapping 2 and 6
Swapping 3 and 5
Run Code Online (Sandbox Code Playgroud)

这应该让你知道代码在做什么.


知道这一点很有帮助

a, b = b, a
Run Code Online (Sandbox Code Playgroud)

交换变量中的值ab.在赋值中,Python首先评估赋值的右侧.然后将值分配给左侧的变量.

所以

list[i], list[len(list) -i -1] =  list[len(list) -i -1], list[i] 
Run Code Online (Sandbox Code Playgroud)

正在交换列表中ilen(list)-i-1索引位置中保存的值.


顺便说一下,命名变量list很糟糕,因为它会影响同名的Python内置.