在Python中,我可以实现一个带有步数计数器和停止条件的循环作为经典案例for loop :
for i in range(50):
result = fun(i)
print(i, result)
if result == 0:
break
where fun(x)
是从整数到整数的任意函数。
我总是怀疑这是否是最好的编码方式(Python地,并就可读性 and 效率)还是最好将其作为while 循环:
i = 0
result = 1
while result != 0 and i < 50:
result = fun(i)
print(i, result)
i += 1
哪种方法更好?特别是 - 我担心的使用break
感觉不对的声明。
The for
循环的性能比while
因为range()是用C实现的 https://stackoverflow.com/a/869295/6260170,同时+=
操作被解释并且需要更多操作 https://stackoverflow.com/a/869347/6260170和对象创建/销毁。您可以使用以下方式说明性能差异timeit module https://docs.python.org/3/library/timeit.html, 例如:
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
The for
循环可以说是在绝大多数情况下,当您希望迭代可迭代对象时,更具Python风格 https://stackoverflow.com/a/920692/6260170。此外,引用Python 维基 https://wiki.python.org/moin/WhileLoop:“由于 Python 中的 for 循环非常强大,因此很少使用 while,除非需要用户输入的情况”。使用 a 并没有什么不符合 Python 风格的break
陈述per se.
可读性主要是主观的,我想说for
循环也更具可读性,但这可能取决于您以前的编程背景和经验。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)