简体   繁体   English

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

[英]python 3.x overwrite previous terminal line

I wrote a simple program to calculate average outcome of a dice throw (pretty pointless, but you have to start somewhere ;P): 我写了一个简单的程序来计算掷骰子的平均结果(毫无意义,但是您必须从某处开始; 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)

To clean it up I want the output to overwrite the previous line. 为了清理它,我希望输出覆盖前一行。 I tried everything I could find, but the only thing I managed to to is to print to the same line without erasing the previous content by changing the last line to: 我尝试了所有可能找到的内容,但是我唯一想做的就是将最后一行更改为:打印到同一行而不擦除以前的内容:

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

which outputs: 输出:

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 /// 

Any ideas? 有任何想法吗?

Add a \\r at the end. 在末尾添加\\r That way, the next line you write will start at the beginning of the previous line. 这样,您编写的下一行将从上一行的开头开始。 And then flush output so it shows immediately. 然后刷新输出,以便立即显示。

Note: If the next line is shorter, the remaining characters will still be there. 注意:如果下一行较短,则其余字符仍在那里。

use end='\\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)

On another note using total = total + random is not a good idea, you are importing the random module and using random as a variable name. 另外要注意,使用total = total + random不是一个好主意,您正在导入random模块,并使用random作为变量名。

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

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