以下代码
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/