我們都知道在Python中執行一段語句的常用方法是使用for
循環。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彼得斯的建議,
.
.
.
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)'。 –
第二種方法的一個主要問題是它爲整個丟棄列表分配存儲空間。 –
但是在實際的代碼中,循環的主體將更加複雜,並且在所有時間中占主導地位。如果迭代變量不重要,則只需旋轉車輪即可。 – hpaulj