Python:'for ... in'语句评估行为(Python: 'for … in' statement evaluation behavior)

编程入门 行业动态 更新时间:2024-10-27 23:31:32
Python:'for ... in'语句评估行为(Python: 'for … in' statement evaluation behavior)

我在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 5

So 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.

更多推荐

本文发布于:2023-07-31 18:46:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1347313.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:语句   Python   statement   behavior   evaluation

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!