想象一下,我有3个团队,并且我想在这3个团队之间进行随机比赛。我使用itertools排列来打印所有匹配项。问题是在游戏中产生分数。想象一下甲队vs乙队(2-1)。如何在比赛中输入A队的2个进球和B队的1个进球?

我已经打印了所有可能的匹配项。请注意,我使用排列是因为A队与B队与B队与A队不同,因为一个团队在主场比赛,而另一场比赛则在另一支球队的主场比赛。

import itertools
import random

teams=['A','B','C']

def games():
  permutations=itertools.permutations(teams,2)
  for i in permutations:
    print(i)
    result=random.randint(0,5)


我的疑问是何时必须在每次迭代中在游戏中生成结果。

最佳答案

您正在生成一个整数,但是需要两个整数来表示匹配分数:

import itertools
import random

teams = ['A','B','C']

def games():
    permutations = itertools.permutations(teams, 2)
    for match in permutations:
        home_team_score, away_team_score = random.randint(0, 5), random.randint(0, 5)
        print(match, home_team_score, away_team_score)

games()


样品输出

('A', 'B') 4 2
('A', 'C') 0 1
('B', 'A') 2 5
('B', 'C') 1 2
('C', 'A') 2 4
('C', 'B') 1 1


然后您可以尝试使用格式,例如

for (home_team, away_team) in permutations:
    home_team_score, away_team_score = random.randint(0, 5), random.randint(0, 5)
    print('{} {} - {} {}'.format(home_team, home_team_score, away_team_score, away_team))


要得到

A 4 - 4 B
A 0 - 4 C
B 3 - 4 A
B 1 - 0 C
C 2 - 1 A
C 3 - 5 B

10-08 12:58