python 3.x覆盖以前的终端线

时间:2014-11-24 21:03:55

标签: python python-3.x command-prompt overwrite

我写了一个简单的程序来计算掷骰子的平均结果(相当无意义,但你必须从某个地方开始; P):

import random, time
from random import randrange

count = 0
total = 0
one_count = 0 

for x in range(10000000):
    random = randrange(1,7)
    count = count + 1
    total = total + random
    average = total / count
    percentage = one_count / count * 100
    if random == 1:
        one_count = one_count + 1
    print("the percentage of ones occurring is", percentage, "and the average outcome is", average)
#   time.sleep(1)

要清理它,我希望输出覆盖前一行。我尝试了所有我能找到的东西,但我唯一能做到的就是打印到同一行而不删除以前的内容,方法是将最后一行更改为:

print("the percentage of ones occuring is", percentage, "and the average outcome is", average, "/// ", end="")

输出:

the percentage of ones occuring is 0.0 and the average outcome is 4.0 /// the percentage of ones occuring is 0.0 and the average outcome is 4.5 /// the percentage of ones occuring is 0.0 and the average outcome is 3.6666666666666665 /// 

有什么想法吗?

2 个答案:

答案 0 :(得分:0)

最后添加\r。这样,您编写的下一行将从上一行的开头开始。然后刷新输出,以便立即显示。

注意:如果下一行较短,剩下的字符仍然在那里。

答案 1 :(得分:0)

使用end='\r

for x in range(100000):
    rnd = randrange(1,7) # don't use random
    count += 1
    total = total + rnd
    average = total / count
    percentage = one_count / count * 100
    if rnd == 1:
        one_count += 1
    print("the percentage of ones occurring is {} and the average outcome is {}".format(percentage,average),end='\r')
    time.sleep(.1)

另一个注意事项使用total = total + random并不是一个好主意,您要导入随机模块并使用随机数作为变量名。