假设我想向一组玩家随机发 52 张编号牌。这是我写的代码:
def deal(players):
deck = [x for x in range(1,53)]
random.shuffle(deck)
internalObject = { 'cards': [], 'score': 0}
starting = dict.fromkeys(players, internalObject)
deckHasCards = True
while (deckHasCards):
for player in players:
if deck == []:
deckHasCards = False
break
card = deck.pop()
starting[player]['cards'].append(card)
card = 0
return starting
问题是,当运行此操作时,所有玩家最终都会持有同一手牌。
def main():
hands = deal(['Jack', 'Jill'])
print(hands)
输出:
{
'Jack': {'cards': [35, 31, 20, 15, 18, 26, 51, 19, 37, 21, 10, 44, 4, 9, 14, 52, 49, 29, 43, 5, 41, 47, 40, 7, 3, 25, 11, 22, 23, 48, 2, 32, 13, 30, 6, 16, 38, 34, 45, 36, 39, 28, 50, 24, 46, 42, 27, 1, 33, 17, 8, 12], 'score': 0},
'Jill': {'cards': [35, 31, 20, 15, 18, 26, 51, 19, 37, 21, 10, 44, 4, 9, 14, 52, 49, 29, 43, 5, 41, 47, 40, 7, 3, 25, 11, 22, 23, 48, 2, 32, 13, 30, 6, 16, 38, 34, 39, 28, 50, 24, 46, 42, 27, 1, 33, 17, 8, 12], 'score': 0}
}
这里的代码有什么问题?为什么 Python 将一张牌分配给所有玩家而不是循环中选择的玩家?
当您执行
dict.fromkeys(players, internalObject)
时,internalObject
字典由reference分配,因此两个玩家都有相同的card/score
集。为了避免在字典理解中为每个用户分配一个新的默认字典。deckHasCards
和 card
(在 while
循环内)。 def deal(players):
deck = [x for x in range(1,53)]
random.shuffle(deck)
player_set = {p: {'cards': [], 'score': 0} for p in players}
while deck:
for player in players:
player_set[player]['cards'].append(deck.pop())
return player_set
def main():
hands = deal(['Jack', 'Jill'])
print(hands)
{'Jack': {'cards': [4, 41, 14, 52, 1, 10, 50, 24, 36, 20, 16, 31, 12, 46, 51, 25, 35, 17, 32, 2, 33, 45, 48, 15, 19, 43], 'score': 0}, 'Jill': {'cards': [5, 30, 49, 44, 38, 9, 28, 22, 27, 42, 39, 13, 7, 37, 8, 34, 47, 23, 29, 11, 26, 18, 40, 21, 6, 3], 'score': 0}}