为什么`mylist [:] = reverse(mylist)`工作?

时间:2015-06-02 18:45:33

标签: python list reverse assign python-internals

以下内容将“就地”反转,并在Python 2和3中运行:

>>> mylist = [1, 2, 3, 4, 5]
>>> mylist[:] = reversed(mylist)
>>> mylist
[5, 4, 3, 2, 1]

为什么/如何?由于reversed给了我一个迭代器而且没有预先复制列表,并且由于[:]=取代了“就地”,我很惊讶。以下,同样使用reversed,按预期中断:

>>> mylist = [1, 2, 3, 4, 5]
>>> for i, item in enumerate(reversed(mylist)):
        mylist[i] = item
>>> mylist
[5, 4, 3, 4, 5]

为什么[:] =不会那样失败?

是的,我知道mylist.reverse()

1 个答案:

答案 0 :(得分:12)

CPython list slice assigment将首先通过调用PySequence_Fast将iterable转换为列表。资料来源:https://hg.python.org/cpython/file/7556df35b913/Objects/listobject.c#l611

 v_as_SF = PySequence_Fast(v, "can only assign an iterable");

即使PyPy做了similar

def setslice__List_ANY_ANY_ANY(space, w_list, w_start, w_stop, w_iterable):
    length = w_list.length()
    start, stop = normalize_simple_slice(space, length, w_start, w_stop)
    sequence_w = space.listview(w_iterable)
    w_other = W_ListObject(space, sequence_w)
    w_list.setslice(start, 1, stop-start, w_other)

此处space.listview将调用ObjSpace.unpackiterable来解包迭代,然后返回列表。