有些时候当我们处理数据的时候,需要显示处理进度:
import sys
from time import sleep
def add1(j):
for n in range(len(j)):
sleep(0.0001)
j[n] = j[n] + 1
sys.stdout.write("\r# Process: %0.1f %%" % (float(n+1) / float(len(j)) * 100))
return j
i = add1(i)
print("\n", i)
# Process: 100.0 %
# [ 2 3 4 ... 9998 9999 10000]
Tips:
1. sys.stdout.write(" ")的本质是print(" ", end="")
# sys.stdout.write("\r# Process: %0.2f %%" % (float(n+1) / float(len(j)) * 100))
print("\r# Process: %0.2f %%" % (float(n+1) / float(len(j)) * 100), end='')
2. 保留小数位数
0.1f --> 保留一位
0.2f --> 保留两位