在Python中,我可以实现一个带有步进计数器的循环和一个停止条件作为for循环的经典案例:
for i in range(50):
result = fun(i)
print(i, result)
if result == 0:
break
Run Code Online (Sandbox Code Playgroud)
fun(x)从整数到整数的任意函数在哪里.
我一直怀疑这是否是编码它的最佳方式(从Python语言,在可读性和效率方面)或者更好地将它作为while循环运行:
i = 0
result = 1
while result != 0 and i < 50:
result = fun(i)
print(i, result)
i += 1
Run Code Online (Sandbox Code Playgroud)
哪种方法更好?特别是 - 我担心使用不合适的break陈述.
Chr*_*nds 14
所述for环是稍微更好的性能比while,因为range()是用C语言实现,同时该+=操作将被解释,并且需要更多的操作和对象创建/破坏.您可以使用该timeit模块说明性能差异,例如:
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
Run Code Online (Sandbox Code Playgroud)
该for循环可以说是当你想遍历一个迭代对象在绝大多数情况下更Python.此外,引用Python维基:"因为Python中的for循环非常强大,但很少使用,除非需要用户输入".关于使用break声明本身没有任何非Pythonic .
可读性主要是主观的,我会说for循环也更具可读性,但它可能取决于您之前的编程背景和经验.
性能略有不同.由于while循环在每次迭代时执行额外的布尔检查,因此稍慢.
但是,对于您想要评估的大多数功能,首先使用循环的替代方法更快.见下面的例子.我确信还有更优化的实施方案..
import time
def fun(step):
return step == 50000000
t1 = time.time()
for i in range(500000000):
result = fun(i)
# print(i, result)
if result == 1:
break
print("time elapsed", time.time() - t1)
t2 = time.time()
i = 0
result = 0
while result != 1 and i < 50000000:
result = fun(i)
# print(i, result)
i += 1
print("and here", time.time() - t2)
import numpy as np
t3 = time.time()
foo = np.arange(500000000)
i = np.where(foo == 50000000)
print("Alternative", time.time()-t3)
Run Code Online (Sandbox Code Playgroud)
时间流逝11.082087516784668
这里是14.429940938949585
替代方案1.4022133350372314
如果你想/必须使用循环,那么for循环通常是更多的Pythonic方式,正如在相关问题的这个很好的答案中所解释的那样
编辑:克里斯兰德斯的答案从C代码的角度解释了它,并使用更准确的(尽管在我强迫这个例子的宏观层面上,这并不重要)计时模块.也请阅读他的答案.