python - 为什么 `for lst in lst:` 有效?

标签 python python-2.7

以下代码

lst = ['foo', 'bar', 'baz']
for lst in lst:
    print lst

给我这个输出

foo
bar
baz

我期望出现错误或以下输出:

['foo', 'bar', 'baz']
['foo', 'bar', 'baz']
['foo', 'bar', 'baz']

上面的代码是错误的,应该是

lst = ['foo', 'bar', 'baz']
for lst_element in lst:
    print lst_element

为什么呢,那个python虽然产生了预期的输出?

最佳答案

在Python中,当你说

for identifier in iterable:

首先将从可迭代对象创建一个迭代器。因此,实际对象不会在循环中使用。然后迭代器将被迭代,当前值将绑定(bind)到名称​​标识符

引用official documentation of for ,

for_stmt ::=  "for" target_list "in" expression_list ":" suite
          ["else" ":" suite]

The expression list is evaluated once; it should yield an iterable object. 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. Each item in turn is assigned to the target list using the standard rules for assignments, and then the suite is executed.

在您的示例中,在最后一次迭代之后,lst 将引用 baz,而不是列表本身,因为 for 循环具有在最后一次迭代中将名称 lst 绑定(bind)到 baz

关于python - 为什么 `for lst in lst:` 有效?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31003661/

相关文章:

python - 如何卸载从 *.txt 文件安装的 pip 包?

python - PyInstance_NewRaw() 与新旧样式类

python - 无法在 python 3.7 中安装包 "retrying"

Python-用下划线替换所有空格并将目录中所有文件转换为小写

python - Django 将查询集序列化为 JSON 以仅使用字段信息和 id 构造 RESTful 响应

带有参数列表的python函数

python - Windows 机器上使用 Python 2.7 和 3.4 的 Pip

python-2.7 - 在python中迭代巨大列表的子列表的有效方法

python - 继承方法的正确方法 1 更正

python反向引用正则表达式