简体   繁体   English

对于python中的循环,在每次迭代时初始化一个外部变量

[英]For loop in python initializes an outer variable on each iteration

I can't understand why the following codes gives different results: 我无法理解为什么以下代码会给出不同的结果:

from datetime import datetime

def foo():
    return {datetime.now() : True}

a = {}
a.update(foo())
a.update(foo())
a.update(foo())

And: 和:

a = {}
for i in xrange(3):
    a.update(foo())

In the former a ends up with three elements, while in the later a ends up with just one element (from the last iteration). 在前a包含三个元素结束,而在后a只有一个元素结束(从最后一次迭代)。

Just your luck. 只是你的运气。 The second code is likely to execute in a single millisecond (or microsecond, depending on your OS), and give three identical datetimes, first is less likely to do so (on your system/your way of executing code). 第二个代码可能在一毫秒(或微秒,取决于您的操作系统)中执行,并提供三个相同的日期时间,首先是不太可能这样做(在您的系统/您执行代码的方式)。 Keep trying, you might end up with two elements. 继续尝试,你最终可能会有两个元素。 Don't write code that depends on luck. 不要编写依赖于运气的代码。

The number of elements you end up with will depend on how many calls to foo Python executes within the granularity of datetime.now() . 你最终得到的元素数量将取决于foo Python在datetime.now()的粒度内执行的调用次数。

If you're running this in an interactive console then between statements executed at the prompt the console will perform housekeeping (for example, displaying the >>> prompt) that will significantly delay the next statement, whereas for the for loop the loop will be executed in its entirety before the console does anything. 如果你在交互式控制台中运行它,那么在提示符处执行的语句之间,控制台将执行内务处理(例如,显示>>>提示符),这将显着延迟下一个语句,而对于for循环,循环将是在控制台执行任何操作之前完整执行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM