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

2024-10-06 12:25:39 发布

您现在位置:Python中文网/ 问答频道 /正文

我的代码生成“结果”列表的随机结果。我正在运行10000+批,我需要一种方法来计算批数,并在底部合计它们。我该怎么做?你知道吗

这是我的密码:

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")

Tags: 方法inimport密码列表fortimerange
2条回答
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摆脱睡眠,因为你只是在拖延程序的执行。你不需要在那里。如果您想让用户在两秒钟内看到正在加载的消息,只需在末尾添加一个pause。你知道吗

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

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

祝你好运,希望这有帮助。你知道吗

相关问题 更多 >