繁体   English   中英

循环结构最佳方法

[英]Looping structure best approach

考虑相同循环结构的以下两个变体:

x = find_number_of_iterations()
for n in range(x):
    # do something in loop

和:

for n in range(find_number_of_iterations()):
    # do something

将在第二循环评估方法find_number_of_iterations在每一个后续循环运行,或将方法find_number_of_iterations甚至在第二个变体只计算一次?

无论哪种方式,该函数仅被调用一次。 您可以演示如下:

>>> def test_func():
    """Function to count calls and return integers."""
    test_func.called += 1
    return 3

# first version
>>> test_func.called = 0
>>> x = test_func()
>>> for _ in range(x):
    print 'loop'


loop
loop
loop
>>> test_func.called
1

# second version
>>> test_func.called = 0
>>> 
>>> for _ in range(test_func()):
    print 'loop'


loop
loop
loop
>>> test_func.called
1

该函数被调用一次,并且调用该函数的结果被传递到range (然后,调用range的结果被迭代); 这两个版本在逻辑上是等效的。

该函数被调用一次。 从逻辑上讲,如果每次迭代都调用它,则循环范围可能会发生变化,从而引起各种破坏。 这很容易测试:

def find_iterations():
    print "find_iterations called"
    return 5

for n in range(find_iterations()):
    print n

结果是:

$ python test.py
find_iterations called
0
1
2
3
4

我怀疑您的导师的困惑可以追溯到Python的for循环的语义与其他语言有很大不同的事实。

在像C这样的语言中,for循环或多或少是while循环的语法糖:

for(i = 0; i < n; i++)
{
   //do stuff
}

等效于:

i = 0;
while(i < n)
{
    //do stuff
    i++
}

在Python中则有所不同。 它的for循环是基于迭代器的。 迭代器对象仅初始化一次,然后在后续迭代中使用。 以下代码片段显示Python的for循环无法(轻松地)转换为while循环,并且还显示了while循环中您的导师的关注是有效的:

>>> def find_number_of_iterations():
    print("called")
    return 3

>>> for i in range(find_number_of_iterations()): print(i)

called
0
1
2

>>> i = 0
>>> while i < find_number_of_iterations():
    print(i)
    i += 1


called
0
called
1
called
2
called

暂无
暂无

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

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