gpt4 book ai didi

python - Python 'for' 循环的更好方法

转载 作者:IT老高 更新时间:2023-10-28 21:40:51 25 4
gpt4 key购买 nike

我们都知道,在 Python 中执行语句一定次数的常用方法是使用 for 循环。

这样做的一般方法是,

# I am assuming iterated list is redundant.
# Just the number of execution matters.
for _ in range(count):
pass

我相信没有人会争辩说上面的代码是常见的实现,但是还有另一种选择。通过引用相乘来利用 Python 列表创建的速度。

# Uncommon way.
for _ in [0] * count:
pass

还有旧的while方式。

i = 0
while i < count:
i += 1

我测试了这些方法的执行时间。这是代码。

import timeit

repeat = 10
total = 10

setup = """
count = 100000
"""

test1 = """
for _ in range(count):
pass
"""

test2 = """
for _ in [0] * count:
pass
"""

test3 = """
i = 0
while i < count:
i += 1
"""

print(min(timeit.Timer(test1, setup=setup).repeat(repeat, total)))
print(min(timeit.Timer(test2, setup=setup).repeat(repeat, total)))
print(min(timeit.Timer(test3, setup=setup).repeat(repeat, total)))

# Results
0.02238852552017738
0.011760978361696095
0.06971727824807639

如果有小的差异我不会发起主题,但是可以看出速度差异是100%。如果第二种方法效率更高,为什么 Python 不鼓励这种用法呢?有没有更好的办法?

测试是使用 Windows 10Python 3.6 完成的。

遵循@Tim Peters 的建议,

.
.
.
test4 = """
for _ in itertools.repeat(None, count):
pass
"""
print(min(timeit.Timer(test1, setup=setup).repeat(repeat, total)))
print(min(timeit.Timer(test2, setup=setup).repeat(repeat, total)))
print(min(timeit.Timer(test3, setup=setup).repeat(repeat, total)))
print(min(timeit.Timer(test4, setup=setup).repeat(repeat, total)))

# Gives
0.02306803115612352
0.013021619340942758
0.06400113461638746
0.008105080015739174

这提供了更好的方法,这几乎回答了我的问题。

为什么这比 range 快,因为两者都是生成器。是因为值(value)永远不会变吗?

最佳答案

使用

for _ in itertools.repeat(None, count)
do something

是获得所有世界中最好的一种非显而易见的方式:微小的恒定空间需求,并且每次迭代都不会创建新对象。在幕后,repeat 的 C 代码使用原生 C 整数类型(不是 Python 整数对象!)来跟踪剩余计数。

因此,计数需要适合平台 C ssize_t 类型,通常在 32 位框上最多为 2**31 - 1 , 在这里是一个 64 位的盒子:

>>> itertools.repeat(None, 2**63)
Traceback (most recent call last):
...
OverflowError: Python int too large to convert to C ssize_t

>>> itertools.repeat(None, 2**63-1)
repeat(None, 9223372036854775807)

这对我的循环来说足够大了 ;-)

关于python - Python 'for' 循环的更好方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46996315/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com