背景 我有这个程序,用户写两个彼此面对的团队和他们的分数,我应该相应地更新一个表。我将所有团队存储为具有参数的对象,例如姓名,游戏,胜利,目标等。
我的问题: 有没有办法让我同时处理团队输入和更新各自的统计数据?现在我正在使用2个不同的for循环,基本上做同样的事情并做一些小调整。
我的程序现在(部分内容): 我将这个用于homeTeam的循环,而另一个用于其他团队。
for i in self.teams:
if homeTeam.lower() == i.name.lower():
i.games += 1
goal_dif_Split = i.goal_dif.split("-")
goal_dif_Split[0] = int(goal_dif_Split[0])+ scoreH
goal_dif_Split[1] = int(goal_dif_Split[1])+ scoreA
i.goal_dif = str(goal_dif_Split[0])+"-"+str(goal_dif_Split[1])
if scoreH > scoreA:
i.win += 1
i.points += 3
elif scoreH < scoreA:
i.loss += 1
else:
i.tie += 1
i.points += 1
根据评论的要求:
1。这就是团队输入的样子:
homeTeam = input ("Hometeam: ")
awayTeam = input ("Awayteam: ")
score = input ("Score: ")
2。这是第二个for循环:
for j in self.teams:
if awayTeam.lower() == j.name.lower():
j.games += 1
goal_dif_Split = j.goal_dif.split("-")
goal_dif_Split[0] = int(goal_dif_Split[0])+ scoreA
goal_dif_Split[1] = int(goal_dif_Split[1])+ scoreH
j.goal_dif = str(goal_dif_Split[0])+"-"+str(goal_dif_Split[1])
if scoreA > scoreH:
j.win += 1
j.points += 3
elif scoreA < scoreH:
j.loss += 1
else:
j.tie += 1
j.points += 1
答案 0 :(得分:0)
一个简单的解决方案 - 为什么不创建一个完全执行循环的函数?
然后 - 只需复制其他团队的函数调用。
答案 1 :(得分:0)
模拟现实。最初,统计表是空的。设为名称为键的字典,stats对象为值。
获得name1 - name2 ... 3:2
后,您必须更新两条记录。你不应该遍历所有的团队。该字典用于按名称搜索值(记录)。类似的东西:
table = {} # initially empty
...
# parse the result to get...
homeTeam = 'red onions'
homeResult = 3
guestTeam = 'blue shits'
guestResult = 2
# Get the stats objects for the teams.
# The Stats() will create the initialized
# statistics object if it does not exist
# for the team, yet.
hs = table.get(homeTeam,Stats())
gs = table.get(guestTeam,Stats())
hs.games += 1
gs.games += 1
# Now make the comparisons and modify the
hs.win += 1
gs.loss += 1
... etc.
更新:如果您想使用列表,那么Bkkknght's solution可能最接近您的初始方法。寻找最有效的解决方案不是目标,因为团队数量很少。
答案 2 :(得分:0)
将两个循环转换为单个循环并不困难:
game_teams = (home_team, away_team)
game_score = score.split("-")
for t in self.teams:
if t in game_teams:
if t == home_team:
scored, allowed = game_score
else: # t == away_team, so reverse the scores
allowed, scored = game_score
# now update t using scored and allowed, rather than the "raw" scores
t.games += 1
if scored > allowed:
t.win += 1
t.points += 3
elif scored == allowed:
t.tie += 1
t.points += 1
else:
t.loss += 1
# etc