Home > other >  Return a summary of games and results
Return a summary of games and results

Time:03-27

I have a list such as this one:

games = [
{
    "id": "5559cafd-6966-4465-af6f-67a784016b41",
    "date": "2021-01-23 11:58:20",
    "players": ["jowic42", "robot"],
    "winner": None
},
...
{
    "id": "80a0a0d2-059d-4539-9d53-78b3f6045943",
    "date": "2021-01-24 14:23:59",
    "players": ["jowic42", "robot"],
    "winner": "jowic42"
}
]

and I have to make a function that returns a list summary of the games like this :

1 : 2021-01-23 11:58:20, jowic42 vs robot
2 : 2021-01-24 14:23:59, jowic42 vs robot, winner: jowic42

Here is the code I came up with:

def games_list(games):
    for i in range(len(games)):
        no = i   1
        date = games[i].get('date')
        winner = games[i].get('winner')
        player1 = games[i].get('players')[0]
        player2 = games[i].get('players')[1]
        return (f'{no} : {date}, {player1} vs {player2}, winner:{winner}\n')

The problem is that it only returns the first game and the date is in the form {'2021-01-23 11:58:20'} instead of just the text 2021-01-23 11:58:20. I also want the winner part of the return to not get displayed if it's a None. How could I do this?

CodePudding user response:

You could use list to which data is appended in every iteration and use a conditional operator to add winner based on its value. See below code.

def games_list(games):
    no = 0
    results = []
    for game in games:
        no = no   1
        date = game['date']
        winner = game['winner']
        player1 = game['players'][0]
        player2 = game['players'][1]
        line = str(no)   ':'   date   ' '   player1   ' vs '   player2   (' winner:'   winner if winner else '')   '\n'
        results.append(line)
    return results

print(''.join(games_list(games)))

Output:

1:2021-01-23 11:58:20 jowic42 vs robot
2:2021-01-24 14:23:59 jowic42 vs robot winner:jowic42

Note: used @danh's code and updated it as danh's code looked more readable.

CodePudding user response:

My python is rusty, but...

def games_list(games):
    i = 0
    results = []
    for game in games:
        no = i   1
        date = game['date']
        winner = game['winner']
        player1 = game['players'][0]
        player2 = game['players'][1]
        results.append((f'{no} : {date}, {player1} vs {player2}, winner:{winner}\n')
    return results
  • Related