Python记分
我一直在做记分员,但我不知道如何将球员变量的数量分配给0。例如,如果有3个玩家,那么我需要给3个不同的变量赋值0。这可能吗?如果是,怎么做?如果没有,我还能怎么做Python记分,python,python-3.x,variables,variable-assignment,Python,Python 3.x,Variables,Variable Assignment,我一直在做记分员,但我不知道如何将球员变量的数量分配给0。例如,如果有3个玩家,那么我需要给3个不同的变量赋值0。这可能吗?如果是,怎么做?如果没有,我还能怎么做 while True: try: numPlayers = int(input("How many people are playing?")) if numPlayers == 0 or numPlayers == 1 or numPlayers > 23: pr
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}
是什么阻止您使用
列表
?使用列表
存储所有玩家的分数,例如:分数=[0]*numPlayers
。然后,scores[0]
将是第一名玩家的分数,scores[1]
第二名玩家的分数,……谢谢!我会看看我是否能使用一个列表,我也会使用字典,看看哪一个更好!