为什么会用hit()方法附加所有双手

问题描述 投票:-3回答:1

BlackjackDeck class

players class, a BlackjackDeck sub class .com / bIwv6.png

an instance of Players class and use of hit() method

使用Python开发二十一点游戏。我的问题是,为什么在测试hit()方法时,会附加所有玩家的手牌,而不只是“ Abi”?

python-3.x
1个回答
0
投票

您的问题在于如何创建手。

hand_holder = [[]] * 7
print(hand_holder)
hand_holder[0].append("test")
print(hand_holder)

这将创建一个列表并进行复制,因此您具有7个相同列表的副本。因此更改1将更改所有这些,因为它们都是相同的列表

输出

[[], [], [], [], [], [], []]
[['test'], ['test'], ['test'], ['test'], ['test'], ['test'], ['test']]

相反,您应该为每个玩家创建新列表,以使更新一个玩家不会影响其他玩家

hand_holder = [[] for _ in range(7)]
print(hand_holder)
hand_holder[0].append("test")
print(hand_holder)

输出

[[], [], [], [], [], [], []]
[['test'], [], [], [], [], [], []]
© www.soinside.com 2019 - 2024. All rights reserved.