【发布时间】:2019-07-11 22:17:41
【问题描述】:
昨天,我决定第一次开始玩 Python,所以请放轻松,我几乎没有编程经验。 作为我的第一个小项目,我正在尝试编写一个脚本,将一副牌洗牌并从洗好的牌堆中处理 5 张牌。 我正在尝试将手存储在二维数组/矩阵中。 这是我遇到问题的代码:
import random
sorted_deck = ["AH","KH","QH","JH","TH","9H","8H","7H","6H","5H","4H","3H","2H",
"AS","KS","QS","JS","TS","9S","8S","7S","6S","5S","4S","3S","2S",
"AD","KD","QD","JD","TD","9D","8D","7D","6D","5D","4D","3D","2D",
"AC","KC","QC","JC","TC","9C","8C","7C","6C","5C","4C","3C","2C"]
def shuffle():
sorted_deck_current = list()
sorted_deck_current.clear()
sorted_deck_current = sorted_deck.copy()
shuffled_deck = list()
shuffled_deck.clear()
for n in range(0,52):
r = random.randrange( 0, len(sorted_deck_current) )
shuffled_deck.append( sorted_deck_current[r] )
sorted_deck_current.pop( r )
return shuffled_deck
for n in range(2): # Check that the shuffle()-function works
fresh_shuffled = shuffle()
print( "Shuffled deck: " + str(fresh_shuffled) )
many_hands = list()
temp_hand = list()
temp_deck = list()
many_hands.clear()
for n in range(5): # Draw 5 hands from freshly shuffled decks
temp_hand.clear()
temp_deck.clear()
temp_deck = shuffle()
for i in range(5):
temp_hand.append( temp_deck[i] )
many_hands.append( temp_hand )
print( many_hands[n] )
for q in range(5): # Try and output the 5 different hands again
print( many_hands[q] )
exit()
我的for n in range(5) 在代码末尾循环输出 5 个不同的手,这就是我想要的。
for q in range(5) 循环输出同一手牌 5 次,这恰好是前一个循环的最后一手牌。
我不知道为什么会这样。
如果有人可以向我解释这种行为,将不胜感激。
【问题讨论】:
-
如果您打印
many_hands的第一个元素,您会注意到它在每次迭代中都会发生变化。所有的手都是同一个对象。 -
many_hands.append( temp_hand )的作用是将many_hands附加到temp_hand的引用。这意味着many_hands[0]现在指向与temp_hand完全相同的列表。因此,当您更改temp_hand,然后再调用many_hands[0]时,您现在指向的是更改后的temp_hand。你这样做了 5 次。
标签: python