我正在编写游戏 Onitama 的python版本,我现在正试图编写一个功能来洗牌:
temp_deck = onitama_deck.deck
print(temp_deck)
print(len(onitama_deck.deck))
print(len(temp_deck))
for i in range(len(temp_deck)):
next_card = temp_deck[random.randrange(0, len(temp_deck))]
deck.deck[i] = next_card
temp_deck.remove(next_card)
print(onitama_deck.deck)
onitama_deck.deck和temp_deck都是列表,但是当我使用包含1-10的值的牌组运行程序时,我得到以下输出:
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
10
10
Traceback (most recent call last):
File "onitama.py", line 33, in <module>
deck.shuffle()
File "onitama.py", line 25, in shuffle
onitama_deck.deck[i] = next_card
IndexError: list assignment index out of range
起初我想知道为什么我太大了,所以我尝试打印两个列表。出于某种原因,从temp_deck中删除每个迭代的最低奇数,然后将onitama_deck.deck设置为等于temp_deck,如下所示:
iteration: 1
temp_deck: [2, 3, 4, 5, 6, 7, 8, 9, 10]
deck: [2, 3, 4, 5, 6, 7, 8, 9, 10]
iteration: 2
temp_deck: [2, 4, 5, 6, 7, 8, 9, 10]
deck: [2, 4, 5, 6, 7, 8, 9, 10]
iteration: 3
temp_deck: [2, 4, 6, 7, 8, 9, 10]
deck: [2, 4, 6, 7, 8, 9, 10]
iteration: 4
temp_deck: [2, 4, 6, 8, 9, 10]
deck: [2, 4, 6, 8, 9, 10]
iteration: 5
temp_deck: [2, 4, 6, 8, 10]
deck: [2, 4, 6, 8, 10]
然后我得到索引超出范围错误。无论如何可以解释我的逻辑中的缺陷?谢谢你的帮助。
答案 0 :(得分:2)
问题是temp_deck
不是副本的副本,而是相同套牌的引用:
temp_deck = onitama_deck.deck
要制作副本,您可以将其更改为:
temp_deck = list(onitama_deck.deck)