我有一个程序可以把它的进度打印到控制台上。每隔20步,它会打印10 20 30等步数,但在此范围内,它会打印一个点。这是使用print语句打印的,末尾带一个逗号(python 2.x)
if epoch % 10 == 0:
print epoch,
else:
print ".",
不幸的是,我注意到这些点是彼此分开打印的,如下所示:
0 . . . . . . . . . 10 . . . . . . . . . 20 . . . . . . . . . 30
我希望它更紧凑,如下所示:
0.........10.........20.........30
在visual basic语言中,如果我们在print语句的末尾添加分号而不是逗号,就可以得到这种形式。在Python中有没有类似的方法来实现这一点,或者通过演练来获得更紧密的输出?
备注:
感谢并尊重所有回复的人,我注意到他们中的一些人认为“时代”的变化发生得很及时。实际上,它不是,因为它发生在完成一些迭代之后,这可能需要几秒钟到几分钟的时间。
发布于 2016-08-24 20:42:40
如果您想对格式进行更多控制,则需要使用以下两种方法之一:
import sys
sys.stdout.write('.')
sys.stdout.flush() # otherwise won't show until some newline printed
。。而不是print
,或者使用Python3print函数。这在以后的Python 2.x版本中可以作为将来的导入使用,如下所示:
from __future__ import print_function
print('.', end='')
在Python3中,可以传递关键字参数flush
print('.', end='', flush=True)
这与上面的两行sys.stdout
具有相同的效果。
发布于 2016-08-24 20:48:20
import itertools
import sys
import time
counter = itertools.count()
def special_print(value):
sys.stdout.write(value)
sys.stdout.flush()
while True:
time.sleep(0.1)
i = next(counter)
if i % 10 == 0:
special_print(str(i))
else:
special_print('.')
发布于 2016-08-24 20:48:50
这里有一个可能的解决方案:
import time
import sys
width = 101
for i in xrange(width):
time.sleep(0.001)
if i % 10 == 0:
sys.stdout.write(str(i))
sys.stdout.flush()
else:
sys.stdout.write(".")
sys.stdout.flush()
sys.stdout.write("\n")
https://stackoverflow.com/questions/39123549
复制相似问题