Python 记分

Python scorekeeping

我一直在做记分员,但我不知道如何将玩家变量的数量分配给 0。例如,如果有 3 个玩家,那么我需要为 3 个不同的变量分配值0.这可能吗?如果是这样,如何?如果没有,我还能怎么做?

while True:
    try:
        numPlayers = int(input("How many people are playing?"))
        if numPlayers == 0 or numPlayers == 1 or numPlayers > 23:
            print("You cannot play with less than 2 people or more than 23 
         people.")

        else:
            break

    except ValueError:
        print("Please enter an integer value.")

for numTimes in range(0, numPlayers):
    #what should i do?

使用字典,像这样:

players = {'player-{}'.format(num): 0 for num in range(1, num_players + 1)}

也许集合中的 defaultdict 更适合这项任务:

from collections import defaultdict

players = defaultdict(int)
players['Dirk']
# Returns 0
players['John'] += 1
print(players)
# Prints {'John': 1, 'Dirk': 0}