gpt4 book ai didi

python - Python 中 'for a[-1] in a' 和 'for a in a' 的区别?

转载 作者:太空宇宙 更新时间:2023-11-03 11:00:03 25 4
gpt4 key购买 nike

在此post , 以下代码片段可能有效。

a = [0, 1, 2, 3]
for a[-1] in a:
print(a[-1])

引用这个answer

While doing for a[-1] in a, you actually iterate through the list and temporary store the value of the current element into a[-1].

同样,我认为做for a in a,它应该遍历列表并将当前元素的值临时存储到a,所以的值>a可以是0,且不可迭代,那么在下一次迭代时会抛出TypeError异常。然而,结果如下。

>>> a = [0, 1, 2, 3]
>>> for a in a:
... print a
...
0
1
2
3
>>> a
3

如何理解?

最佳答案

引用official documentation on for loop ,

An iterator is created for the result of the expression_list. The suite is then executed once for each item provided by the iterator, in the order of ascending indices.

因此,当您迭代一个对象时,会创建一个迭代器对象并用于迭代。这就是为什么原始对象不会丢失,至少在循环运行之前不会丢失。

在您的例子中,当执行 for a in a: 时,首先为 a 创建一个迭代器对象,然后从迭代器对象中检索值。即使循环在每次迭代中将名称 a 绑定(bind)到某个其他值,迭代器对象仍然持有对原始列表对象的引用,并从中给出值。这就是您没有收到任何错误的原因。

关于python - Python 中 'for a[-1] in a' 和 'for a in a' 的区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34706506/

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