python - 足球队联赛

标签 python python-itertools

假设我有 3 支球队,我想在三支球队之间生成随机比赛。我使用 itertools 排列来打印所有匹配项。问题是在游戏中生成分数。想象一下 A 队对阵 B 队 (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

关于python - 足球队联赛,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56382837/

相关文章:

Python Itertools : Complex "product"

python - 列表理解方法优化

python - 循环滑动窗口迭代

python - 如何从两个列表中删除特定独立游戏的某些元素的元素?

python - 如何从函数而不是yield 运行Tornado's Future

python - 如何使用 Django 从 .py 文件中读取媒体文件?

python - 如何运行 python 脚本?

python - 让 PostgreSQL 尊重输入参数的顺序?

python - Itertools 链在 Cython 中的行为有所不同

python - 如何将参数传递给要传递给 itertools.groupby 的 keyfunc?