im trying to make a program to iterate through af list of lists containing 2 dictionaries with team informations of soccerteams. I want to get the match's winner from using for loops. My list looks like this:
matches = [[{'name': 'team bob', 'score': 3},
{'name': 'team mia', 'score': 4}
],
[{'name': 'team eva', 'score': 0},
{'name': 'team storm', 'score': 4}
],
[{'name': 'team storm', 'score': 0},
{'name': 'team mia', 'score': 2}
],
[{'name': 'team bob', 'score': 4},
{'name': 'team storm', 'score': 4}
]]
and here ive tried on maked some for loops but i cant figure out why i cant iterate correctly through them to check each match for the winner. This is what ive come up with
def scoredMost(matches):
for match in matches:
for team in match:
print(team)
scoredMost(matches)
CodePudding user response:
This would print the winner of each match, not sure if this is all that you wanted
def scoredMost(matches):
# THIS JUST PRINTS THE WINNER
for match in matches:
print("Winner of match is ", end='')
if match[0]['score'] > match[1]['score']:
print(f"{match[0]['name']} with a score of {match[0]['score']}")
elif match[0]['score'] < match[1]['score']:
print(f"{match[1]['name']} with a score of {match[1]['score']}")
else:
print("Tie")
CodePudding user response:
The may give you an idea of how you can navigate these lists and dictionaries:
matches = [[{'name': 'team bob', 'score': 3},
{'name': 'team mia', 'score': 4}
],
[{'name': 'team eva', 'score': 0},
{'name': 'team storm', 'score': 4}
],
[{'name': 'team storm', 'score': 0},
{'name': 'team mia', 'score': 2}
],
[{'name': 'team bob', 'score': 4},
{'name': 'team storm', 'score': 4}
]]
for teamA, teamB in matches:
if teamA['score'] == teamB['score']:
print(f'Match tied between {teamA["name"]} and {teamB["name"]}')
elif teamA['score'] > teamB['score']:
print(f'{teamA["name"]} beat {teamB["name"]}')
else:
print(f'{teamB["name"]} beat {teamA["name"]}')
Output:
team mia beat team bob
team storm beat team eva
team mia beat team storm
Match tied between team bob and team storm