我可能没有使用正确的关键字来找到有用的东西(您可能会从尴尬的标题中看出来),所以就这样:
如何从一个列表中表示对的值?例如,列表可以是一组互相竞争的球队(例如, Red , Gold 和 Blue )。重视每个游戏的结果。每个列表项(团队)都与所有其他项配对,并且每个配对都对应一个值,我们可以将其称为结果。通常,使用这种结构的方式是挑选两支球队来查找比赛结果。双人不设顺序,球队没有特殊地位。
最明显的是一个表(例如,我使用的是Pandas,所以是一个数据框),但感觉有点尴尬,因为如果要避免重复,它必须是半满的。
“团队”之间可能有两个“游戏”(无论如何,这在体育运动中很常见),但在这种情况下,我认为一张桌子会更糟,因为我们必须为对角线上方和下方的部分(例如“第1轮”和“第2轮”),并且不能推广到更多匹配项(应在“单”列表的顶部添加一个附加变量)。
用什么“自然”(代替一个更好的术语)来表示呢? (通过 this 表示原始表格,即单个列表中的无序对。)
P.S。:我提到了数据框,但该问题适用于任何类型的“表格”(例如,字典中的字典)。
P.S.2 :我提到“团队”只是出于说明目的。请避免讨论与体育有关的问题!
答案 0 :(得分:1)
我认为最好制造物体。
在python文件中:
class Team():
def __init__(self, name):
self.name = name
def __str__(self):
return str(self.name)
class Game():
def __init__(self, team_1, team_2, result):
self.team_1 = team_1
self.team_2 = team_2
self.result = result
def __str__(self):
return f"{self.team_1} vs {self.team_2}: {self.result}"
# some tests
if __name__ == "__main__":
red, gold, blue = Team("red"), Team("gold"), Team("blue")
red_blue = Game(red, blue, "v1")
red_gold = Game(red, gold, "v2")
blue_gold = Game(blue, gold, "v3")
print(red_blue, red_gold, blue_gold, sep="\n")
如果执行文件,它将输出:
red vs blue: v1
red vs gold: v2
blue vs gold: v3
编辑:职业联赛
# add this code in the same module that the previous one
class League():
def __init__(self, name):
self.name = name
self.teams = []
self.games = []
def add_teams(self, *teams):
# *teams is a sequence of Team instances
for team in teams:
self.teams.append(team)
def add_games(self, *games):
# *games is a sequence of Game instances
for game in games:
self.games.append(game)
def get_game_by_team(self, team):
print(f"Results for all games of {team} in {self.name} league:")
for game in self.games:
if team == game.team_1.name or team == game.team_2.name:
print(game)
if __name__ == "__main__":
league = League("master")
league.add_teams(red, gold, blue)
league.add_games(red_blue, red_gold, blue_gold)
league.get_game_by_team("red")
league.get_game_by_team("blue")
league.get_game_by_team("gold")
它输出:
Results for all games of red in master league:
red vs blue: v1
red vs gold: v2
Results for all games of blue in master league:
red vs blue: v1
blue vs gold: v3
Results for all games of gold in master league:
red vs gold: v2
blue vs gold: v3
是回答您的问题吗?
如果您希望像第一个问题中所示那样显示更直观的表,则尝试制作GUI应该更有效。
答案 1 :(得分:0)
我建议使用字典的字典,
例如,
{'red':{'gold':'v1','blue':'v2'},'gold':{'red':'v4','blue':'v3'},'blue':{'red':'v5','gold':'v6'}}
也就是说,
match = 0
>>> def get_next_match():
... global match
... match+=1
... return match
...
>>> {team:{t:get_next_match() for t in teams if t!=team} for team in teams}
{'blue': {'gold': 6, 'red': 5}, 'gold': {'blue': 4, 'red': 3}, 'red': {'blue': 2, 'gold': 1}}