结束循环,带有计数器和条件 [英] End loop with counter and condition

查看:52
本文介绍了结束循环,带有计数器和条件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Python中,我可以实现带有步数计数器和停止条件的循环,这是 for循环的经典情况:

In Python I can implement a loop with step counter and a stop condition as a classical case of for loop :

for i in range(50):
    result = fun(i)
    print(i, result)
    if result == 0: 
        break

其中 fun(x) 是从整数到整数的任意函数.

where fun(x) is some arbitrary function from integers to integers.

我一直在怀疑这是最好的编码方式( Python ,并且就可读性效率而言)还是最好将其作为 while 循环 运行:

I always in doubts if that is the best way to code it (Pythonically, and in terms of readability and efficiency) or is it better to run it as a while loop:

i = 0
result = 1
while result != 0 and i < 50:
    result = fun(i)
    print(i, result)
    i += 1

哪种方法更好?特别是-我担心 break 语句的用法不正确.

which approach is better? In particular - I'm concerned about the usage of break statement which doesn't feel right.

推荐答案

for 循环的性能比 while 略高,因为更多操作和对象创建/销毁.您可以使用 timeit 模块来说明性能差异.,例如:

The for loop is slightly more performant than the while because range() is implemented in C, meanwhile the += operation is interpreted and requires more operations and object creation/ destruction. You can illustrate the performance difference using the timeit module, for example:

from timeit import timeit

def for_func():
    for i in range(10000):
        result = int(i)
        if result == -1: 
            break

def while_func():
    i = 0
    result = 1
    while result != -1 and i < 10000:
        result = int(i)
        i += 1


print(timeit(lambda: for_func(), number = 1000))
# 1.03937101364
print(timeit(lambda: while_func(), number = 1000))
# 1.21670079231 

对于 for 循环,可以说是在大多数情况下,当您希望遍历一个可迭代的对象.此外,引用 Python Wiki :由于Python中的for循环是如此强大,而除非需要用户输入,否则很少使用."使用 break 语句本身并没有非Python风格.

The for loop is arguably more Pythonic in the vast majority of cases when you wish to iterate over an iterable object. Furthermore, to quote the Python wiki: "As the for loop in Python is so powerful, while is rarely used except in cases where a user's input is required". There is nothing un-Pythonic about using a break statement per se.

可读性主要是主观的,我想说 for 循环也更具可读性,但这可能取决于您以前的编程背景和经验.

Readability is mostly subjective, I would say the for loop is more readable too, but it probably depends on your previous programming background and experience.

这篇关于结束循环,带有计数器和条件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆