我經常需要運行大量的維護腳本,我總是在代碼中插入以跟蹤任何迭代的進度。用於進度計數的Python模式
c = len(sequence)
i = 1
for s in sequence:
print "{}/{}".format(i,c)
i+=1
# Do something
是否有更優雅的& Python的方式來這段代碼轉換爲可重複使用彭定康?
我經常需要運行大量的維護腳本,我總是在代碼中插入以跟蹤任何迭代的進度。用於進度計數的Python模式
c = len(sequence)
i = 1
for s in sequence:
print "{}/{}".format(i,c)
i+=1
# Do something
是否有更優雅的& Python的方式來這段代碼轉換爲可重複使用彭定康?
for i, s in enumerate(sequence):
print "{}/{}".format(i,c)
#do stuff
要信號級數出總的但是你會prabably要start
1(枚舉需要start=1
作爲參數)
雖然如果你也會發現你經常使用這個精確的打印語句,你可以把它包裝在一個生成器中。
def verbose_enuemrate(seq):
total = len(seq)
#print "starting verbose_enumerate with:", seq
for i,item in enumerate(seq, start=1):
print("{}/{}".format(i,total))
yield i,item
#print "finished verbose_enumerate of:", seq
>>> for i,c in verbose_enuemrate("abc"):
print(c)
1/3
a
2/3
b
3/3
c
請嘗試以下代碼以顯示同一行上的進度。
import time
print "Work in progress(0%%)", # Python 2 print without newline
for work_done in range(10):
print "\b\b\b\b\b%2d%%)" % work_done, # Backspace then overwrite
time.sleep(1) # or do some work
OP希望使代碼更容易編寫/重用,而不是提高用戶的顯示效果。 –
我也很歡迎這個解決方案,它確實增加了價值 – nehemiah
當我第一次評論時,我錯過了「維護」部分,我認爲打印迭代是爲了調試,但是看到我錯了,這是非常好的建議! –
['enumerate'(https://docs.python.org/2/library/functions.html#enumerate)(我主動寫一個更完整的答案) –
噢,其他方法嗎? – nehemiah