收集数据时的Python循环

时间:2013-12-05 14:57:17

标签: python loops tkinter counter average

我有一个NFL模拟器,根据几个变量运行并为两个团队吐出一个分数,但我希望模拟器更准确。我试图让它运行100次,计算每个团队赢得的次数,同时还跟踪每个模拟中每个团队的得分,然后产生他们的平均得分。我对如何收集分数然后将它们全部加在一起并且除以100有点迷失。此外,如何在循环中为团队分配“胜利”。

    def calc(self):
        selected_indexA = teams.index(self.var1.get())

        PowerRankA = power_rankings[selected_indexA]
        WinPercA = winning_percentage[selected_indexA] * 100
        LuckA = random.randrange(0,25)
        HomeBonus = 10

        selected_indexB = teams.index(self.var2.get())

        PowerRankB = power_rankings[selected_indexB]
        WinPercB = winning_percentage[selected_indexB] * 100
        LuckB = random.randrange(0,25)
        HomeBonus = 10

        TeamAScore = (PowerRankA + WinPercA + LuckA) / 3
        TeamBScore = (PowerRankB + WinPercB + LuckB + HomeBonus) / 3

        self.lblScoreA["text"] = int(TeamAScore)
        self.lblScoreB["text"] = int(TeamBScore)

    def sim(self):
        count = 0
        while count <= 100:
            if TeamAScore > TeamBScore:
                self.lblWinsA = 1
            else:
                self.lblWinsB = 1
            count +=1

1 个答案:

答案 0 :(得分:1)

您可以在for循环中模拟100个游戏和总和分数,然后除以100

TeamAScore = 0
TeamBScore = 0

TeamAWins = 0
TeamBWins = 0
NoWins = 0

for i in range(100):
    LuckA = random.randrange(0,25)
    LuckB = random.randrange(0,25)

    ScoreA = (PowerRankA + WinPercA + LuckA) / 3
    ScoreB = (PowerRankB + WinPercB + LuckB + HomeBonus) / 3

    TeamAScore += ScoreA
    TeamBScore += ScoreB

    if ScoreA > ScoreB:
        TeamAWins += 1
    elif ScoreA < ScoreB:
        TeamBWins += 1
    else:
        NoWins += 1


TeamAScore /= 100.0
TeamBScore /= 100.0

print "Avg. Score for TeamA:", TeamAScore, " number of Wins:", TeamAWin
print "Avg. Score for TeamB:", TeamBScore, " number of Wins:", TeamBWin
print "No Wins:", NoWins

如果您需要记住所有分数,请使用list.append()

TeamA_All_Scores = [] # list for all scores
TeamB_All_Scores = [] # list for all scores

TeamAWins = 0
TeamBWins = 0
NoWins = 0

for i in range(100):
    LuckA = random.randrange(0,25)
    LuckB = random.randrange(0,25)

    ScoreA = (PowerRankA + WinPercA + LuckA) / 3
    ScoreB = (PowerRankB + WinPercB + LuckB + HomeBonus) / 3

    TeamA_All_Scores.append(ScoreA)
    TeamB_All_Scores.append(ScoreB)

    if ScoreA > ScoreB:
        TeamAWins += 1
    elif ScoreA < ScoreB:
        TeamBWins += 1
    else:
        NoWins += 1


TeamAScore = sum(TeamA_All_Scores) / 100.0
TeamBScore = sum(TeamB_All_Scores) / 100.0

print "Avg. Score for TeamA:", TeamAScore, " number of Wins:", TeamAWin
print "Avg. Score for TeamB:", TeamBScore, " number of Wins:", TeamBWin
print "No Wins:", NoWins
print "TeamA All Scores:", ",".join(TeamA_All_Scores)
print "TeamB All Scores:", ",".join(TeamB_All_Scores)