Python“for”循环的更好方法 - python

我们都知道,在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 10 Python 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快,因为两者都是生成器。是因为价值永远不变吗?

参考方案

使用

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

获得最佳状态的一种显而易见的方法是:微小的恒定空间需求,并且每次迭代都不会创建新的对象。在幕后,repeat的C代码使用本机C整数类型(不是Python整数对象!)来跟踪剩余计数。

因此,该计数需要适合平台C的ssize_t类型,通常在32位盒中(此处为64位盒)中最多为2**31 - 1:

>>> 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 uuid4,如何限制唯一字符的长度 - python

在Python中,我正在使用uuid4()方法创建唯一的字符集。但是我找不到将其限制为10或8个字符的方法。有什么办法吗?uuid4()ffc69c1b-9d87-4c19-8dac-c09ca857e3fc谢谢。 参考方案 尝试:x = uuid4() str(x)[:8] 输出:"ffc69c1b" Is there a way to…

Python-crontab模块 - python

我正在尝试在Linux OS(CentOS 7)上使用Python-crontab模块我的配置文件如下:{ "ossConfigurationData": { "work1": [ { "cronInterval": "0 0 0 1 1 ?", "attribute&…

Python:检查是否存在维基百科文章 - python

我试图弄清楚如何检查Wikipedia文章是否存在。例如,https://en.wikipedia.org/wiki/Food 存在,但是https://en.wikipedia.org/wiki/Fod 不会,页面只是说:“维基百科没有此名称的文章。”谢谢! 参考方案 >>> import urllib >>> prin…

Python GPU资源利用 - python

我有一个Python脚本在某些深度学习模型上运行推理。有什么办法可以找出GPU资源的利用率水平?例如,使用着色器,float16乘法器等。我似乎在网上找不到太多有关这些GPU资源的文档。谢谢! 参考方案 您可以尝试在像Renderdoc这样的GPU分析器中运行pyxthon应用程序。它将分析您的跑步情况。您将能够获得有关已使用资源,已用缓冲区,不同渲染状态上…

Python Pandas导出数据 - python

我正在使用python pandas处理一些数据。我已使用以下代码将数据导出到excel文件。writer = pd.ExcelWriter('Data.xlsx'); wrong_data.to_excel(writer,"Names which are wrong", index = False); writer.…