繁体   English   中英

python 3.x覆盖前一个终端行

[英]python 3.x overwrite previous terminal line

我写了一个简单的程序来计算掷骰子的平均结果(毫无意义,但是您必须从某处开始; 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 /// 

有任何想法吗?

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

注意:如果下一行较短,则其余字符仍在那里。

使用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不是一个好主意,您正在导入random模块,并使用random作为变量名。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM