首页 > 解决方案 > 如何在 Python 的字典中使用相同的“键”更新多个对象?

问题描述

所以,我目前对 Python 有一个(独特的)问题:

我有看起来像这样的构造函数:

 def __init__(self, team, opponent, goals_scored,
                 ball_possession, pass_accuracy, points=0):
        self.team = team
        self.opponent = opponent
        self.__goals_scored = goals_scored
        self.__ball_possession = ball_possession
        self.__pass_accuracy = pass_accuracy
        self.points = points #not from csv, but rest of the fields are

所以我决定添加积分列来跟踪​​每个团队的积分。

我有两个功能可以为我做到这一点:

    def set_victory_points(self):
        """Setter for victory teams"""
        # Assign 3 points to every team that wins
        return self.get_points() + 3

    def set_tie_victory_points(self):
        """Setter for tie teams"""
        return self.get_points() + 1

这些函数依次由主驱动程序调用,如下所示:

def get_victories(team_one, team_two):
    victors = []
    losers = []
    tie_match = []
    for i, row in enumerate(team_one):
        team_1 = Team(team=team_one[i]["Team"],
                      opponent=team_one[i]["Opponent"],
                      goals_scored=team_one[i]["Goals Scored"],
                      ball_possession=team_one[i]["Ball Possession (%)"],
                      pass_accuracy=team_one[i]["Pass Accuracy (%)"])
        team_2 = Team(team=team_two[i]["Team"],
                      opponent=team_two[i]["Opponent"],
                      goals_scored=team_two[i]["Goals Scored"],
                      ball_possession=team_two[i]["Ball Possession (%)"],
                      pass_accuracy=team_two[i]["Pass Accuracy (%)"])

        # Keep track of victors
        if team_1.get_goals_scored() > team_2.get_goals_scored():
            victors.append(team_1.get_team())
            losers.append(team_2.get_team())
            team_1.set_points(team_1.set_victory_points())

        # Keep track of tied matches
        elif team_1.get_goals_scored() == team_2.get_goals_scored():
            tie_match.append(team_1.get_team())
            tie_match.append(team_2.get_team())
            team_1.set_points(team_1.set_tie_victory_points())
            team_2.set_points(team_2.set_tie_victory_points())

        # Keep track of losers
        elif team_1.get_goals_scored() < team_2.get_goals_scored():
            victors.append(team_2.get_team())
            losers.append(team_1.get_team())
            team_2.set_points(team_2.set_victory_points())

我遇到的问题是列表中有多个字典具有相同的团队名称,但这些点不会从字典转移到字典。

例如:第 1 次迭代 Team A 得分比 Team B 多,所以我给 Team A 分配 3 分,但第 2 次游戏 Team B 与 Team A 平分秋色,所以当我去更新对象时,我注意到 Team A 有 0 分,而不是3分。我知道这是因为这次 A 队周围是一个新对象,因此将获得 0 分。

我的问题是我将如何有效地更新字典列表中对团队 A 的所有“积分”引用,以便他们的积分在每次迭代后持续存在?

第 1 次迭代 - A 队得 3 分,B 队 0 队 第 2 次迭代 - B 队得 3 分,A 队 3

这是我的数据的样子:


list=[{'Team': 'A', 'Opponent': 'B', 'Pass Accuracy (%)': '78', 'Goals Scored': '5', 'Ball Possession (%)': '40'}, ## Team One
{'Team': 'B', 'Opponent': 'A', 'Pass Accuracy (%)': '78', 'Goals Scored': '0', 'Ball Possession (%)': '60'}, ## Team Two

{'Team': 'B', 'Opponent': 'A', 'Pass Accuracy (%)': '78', 'Goals Scored': '2', 'Ball Possession (%)': '67'}, ##Team One
{'Team': 'A', 'Opponent': 'B', 'Pass Accuracy (%)': '78', 'Goals Scored': '0', 'Ball Possession (%)': '33'}] ##Team Two

谢谢!

标签: pythonloopsdictionary

解决方案


在我看来,您正在混淆您的抽象。ATeam应该是一个始终存在的对象,其统计信息存储为可能发生变异的属性,但不会为您数据中记录的每个游戏创建多次。换句话说,应该为程序中的每个团队创建一次 Team 对象,而不是多次。

所以我认为你应该回顾一下你的代码与感兴趣的对象的划分方式。这是您可以做什么的代码和伪代码的混合。这不一定是最佳方式,但我正试图尽可能地接近你的当前状态。

class Team:
    def __init__(self, name, points=0, games = []):
        self.name = name
        self.points = points
        self.games = games          # list of games that team played


    def calculate_team_result(self, games):
        """ Takes in a list of games_results & update the 
             team's statistic accordingly """

        for game in games:                          # that's one of your csv row from games_results

            if self.name == game['Team']:           # that's this team's results
                games_pts = get_victory_points(game)    # some method/way you use to calculate the points for that game
                self.points += games_pts

                # you could also update the other stats here if you want 
                self.games.append(game)             # if you wanna keep track of all the games played by that team for later use


class Game:         # your Team class was really a Game imo
    def __init__(self, team, opponent, goals_scored,
                 ball_possession, pass_accuracy, points=0):
        self.team = team
        self.opponent = opponent
        self.__goals_scored = goals_scored
        self.__ball_possession = ball_possession
        self.__pass_accuracy = pass_accuracy
        self.points = points  # not from csv, but rest of the fields are



games_results =[{'Team': 'A', 'Opponent': 'B', 'Pass Accuracy (%)':78, 'Goals Scored': 5, 'Ball Possession (%)': 40}, ## Team One
{'Team': 'B', 'Opponent': 'A', 'Pass Accuracy (%)': '78', 'Goals Scored': '0', 'Ball Possession (%)': 60}, ## Team Two

{'Team': 'B', 'Opponent': 'A', 'Pass Accuracy (%)': 78, 'Goals Scored': 2, 'Ball Possession (%)': 67}, ##Team One
{'Team': 'A', 'Opponent': 'B', 'Pass Accuracy (%)': 78, 'Goals Scored': 0, 'Ball Possession (%)': 33}] ##Team Two

team_a = Team("A", points=0, games=[])
team_b = Team("B", points=0, games=[])
games = []

for game_csv in games_results:
    games.append(Game(game_csv))


# now you have a list of Game objects that details what happened. Pass them to your teams so that they extract the data
# they are interested in from them

team_a.calculate_team_result(games)
team_b.calculate_team_result(games)

我不确定您对 OOP 编程有多满意,但是您的(新)游戏类可能有不同的方法来返回不同的统计信息。例如,在 Game 类中:

def get_team_points(team_name):
    # calculates if the team_name has won, tied or lost & returns the number of points

推荐阅读