gpt4 book ai didi

python - 为什么 `mylist[:] = reversed(mylist)` 有效?

转载 作者:太空狗 更新时间:2023-10-29 18:03:45 28 4
gpt4 key购买 nike

以下“就地”反转列表并在 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()

最佳答案

CPython 列表切片赋值将首先通过调用 PySequence_Fast 将可迭代对象转换为列表。 .来源: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解压可迭代对象,后者又返回一个列表。

关于python - 为什么 `mylist[:] = reversed(mylist)` 有效?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30604127/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com