从可能的结果列表中随机选择时,计算某个结果出现的次数

Count # of times a certain outcome appears when randomly selecting from a list of possible outcomes

我的代码生成列表的随机结果 "outcomes"。我是 运行 批 10,000+,我需要一种方法来计算批次并在底部对它们进行总计。我该怎么做?

这是我的代码:

import random
import time
from time import sleep
outcomes = ['TT','Tt','Tt','tt']
for x in range (0, 5):  
    b = "LOADING OUTCOMES" + "." * x
    print (b, end="\r") 
    time.sleep(0.5)
print("4 Possible Genetic Outcomes Will Be Shown. . . ") ; sleep(1)
for x in range (0, 10000):
    print(random.choice(outcomes))
    time.sleep(0.001)        
x=input("Done determining outcomes!! Press enter to close")
from collections import Counter
from random import choice

outcomes = ["TT", "Tt", "Tt", "tt"]

totals = Counter(choice(outcomes) for _ in range(10000))

给出类似

的东西
Counter({'TT': 2528, 'Tt': 4914, 'tt': 2558})

这是使用您在屏幕截图中提供的代码。这是我将如何去做。检查此解决方案是否适合您。下次请将代码放在问题本身中,而不是作为图像。它会吸引更多的人来帮助你,因为他们可以复制粘贴你的代码并更快地帮助你,而不是自己输入你的代码。

我是怎么解决的: 已经使用列表中的可能选项预定义了一个字典。每次出现选择时,只需将计数器加 1。最后打印所有可能性。您可以使用循环来执行此操作,但由于只有 3 个元素,我决定将它们打印出来。

import random
import time
from time import sleep

outcomes = ["TT", "Tt", "Tt", "tt"]
outcomesCount = {"TT":0, "Tt":0, "tt":0}

for x in range(0,5):
    b = "LOADING OUTCOMES" + "." * x
    print(b, end="\r")
    time.sleep(0.5)
print("4 Possible Genetic Outcomes Will Be Shown. . . ")
sleep(1)

for x in range(0,10000):
    choice = (random.choice(outcomes))
    time.sleep(0.001)
    outcomesCount[choice] += 1
    print(choice) #This is something you were doing in original code. I would not do this because there are too many print statements, and will cause the program to run for a while.

print("The number of times each outcome appeared was: ")
print("TT : %s" %(outcomesCount["TT"]))
print("Tt : %s" %(outcomesCount["Tt"]))
print("tt : %s" %(outcomesCount["tt"]))
x = input("Done determining outcomes!! Press enter to close")

上述程序运行的输出是注意这只是最后的打印语句:

The number of times each outcome appeared was: 

TT : 2484
Tt : 4946
tt : 2570
Done determining outcomes!! Press enter to close

改进: 1.摆脱睡眠,因为你只是在延迟程序执行。你在那里不需要它。如果您希望用户看到加载消息一秒或两秒,您可以在最后添加 1 个暂停。

  1. 第二个for循环中的sleep根本不需要。这是一台计算机,能够做令人惊奇的事情。与它所能处理的相比,这算不了什么。

  2. 不要打印所有结果,因为它将打印 10000 个不同的行。

祝你好运,希望对你有所帮助。