我在Python中有以下代码示例:
def get_objects(): print 'Called get_objects' return [1, 2, 3, 4, 5] def main(): for i in get_objects(): print i main()输出如下:
Called get_objects 1 2 3 4 5所以我的问题是为什么get_objects()只调用一次? 为什么每次迭代都没有获取数据?
I have following code sample in python:
def get_objects(): print 'Called get_objects' return [1, 2, 3, 4, 5] def main(): for i in get_objects(): print i main()Output for this as following:
Called get_objects 1 2 3 4 5So my question is why get_objects() called only once? Why it is not fetched data every time of itteration?
最满意答案
因为这正是Python for循环的工作原理。 in运算符右侧的表达式(在评估时必须返回一个可迭代表达式)仅在循环开始之前计算一次 。 然后,for循环遍历该评估返回的迭代器。
以下是文档 *的摘录:
for语句用于迭代序列的元素(如字符串,元组或列表)或其他可迭代对象:
for_stmt ::= "for" target_list "in" expression_list ":" suite ["else" ":" suite]表达式列表被评估一次 ; 它应该产生一个可迭代的对象。
*注意:我添加了粗体。
Because that is exactly how for-loops work in Python. The expression on the right of the in operator (which must return an iterable when evaluated) is evaluated only once, before looping commences. Then, the for-loop loops over the iterable returned by that evaluation.
Below is an excerpt from the docs*:
The for statement is used to iterate over the elements of a sequence (such as a string, tuple or list) or other iterable object:
for_stmt ::= "for" target_list "in" expression_list ":" suite ["else" ":" suite]The expression list is evaluated once; it should yield an iterable object.
*Note: I added the bold.
更多推荐
发布评论