Python 在循环中附加到列表会重置列表

Python 在循环中附加到列表会重置列表,python,Python,这是我的密码: deckTypes = [] cardType = ["Spade", "Hearts", "Diamonds", "Clubs"] cardValues = ["Ace", 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, "J", "Q", "K"] Values = [[1, 11], 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10] for i in cardType: for j in cardValues:

这是我的密码:

deckTypes = []
cardType = ["Spade", "Hearts", "Diamonds", "Clubs"]
cardValues = ["Ace", 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, "J", "Q", "K"]
Values = [[1, 11], 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10]
for i in cardType:
    for j in cardValues:
        deckTypes.append(str(j) + " of " + str(i))
deck = dict(zip(deckTypes, Values*4))
z = 0
while z < 5:
    card = random.choice(list(deck))
    handValue = deck[card]
    hand = []
    hand.append(card)
    print(hand)
    z += 1
我怎样才能做到这样

['1 of Spade', '3 of Spade', '2 of Clubs', 'K of Hearts', '4 of Spade']

PS:这不是全部代码,但我试图尽可能清楚地理解您将
手的初始化放错了位置


对于当前代码,
hand
在每次迭代期间设置为
[]

['1 of Spade']
['1 of Spade', '3 of Spade']
['1 of Spade', '3 of Spade', '2 of Clubs']
['1 of Spade', '3 of Spade', '2 of Clubs', 'K of Hearts']
['1 of Spade', '3 of Spade', '2 of Clubs', 'K of Hearts', '4 of Spade']

相反,您应该在循环之前初始化
hand
,如下所示:

hand = [] # Executed once, before iterating
z = 0
while z < 5:
    hand.append(card)
    print(hand)
    z += 1
当您退出循环时,
hand
根据需要包含以下列表:

['1 of Spade', '3 of Spade', '2 of Clubs', 'K of Hearts', '4 of Spade']

与您的代码输出在这里

['3 of Hearts']
['9 of Spade']
['3 of Spade']
['Ace of Diamonds']
['Q of Clubs']
但是,当您移动hand=[]并按如下方式从while循环中打印(hand)时

deckTypes = []
cardType = ["Spade", "Hearts", "Diamonds", "Clubs"]
cardValues = ["Ace", 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, "J", "Q", "K"]
Values = [[1, 11], 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10]
for i in cardType:
    for j in cardValues:
        deckTypes.append(str(j) + " of " + str(i))
deck = dict(zip(deckTypes, Values*4))
z = 0
hand = []
while z < 5:
    card = random.choice(list(deck))
    handValue = deck[card]
    hand.append(card)
    z += 1
print(hand)

hand=[]
移动到
之外,同时
。哇,我怎么没有看到您正在将列表初始化到[],然后添加一张卡-其中最多会有一张这样的卡。Vting以打字错误结束-这种问题每周都会出现:)找不到重复,但如果您不知道可能需要阅读:)请不要以图像形式包含输出。将文本作为文本包含。
['1 of Spade', '3 of Spade', '2 of Clubs', 'K of Hearts', '4 of Spade']
['3 of Hearts']
['9 of Spade']
['3 of Spade']
['Ace of Diamonds']
['Q of Clubs']
deckTypes = []
cardType = ["Spade", "Hearts", "Diamonds", "Clubs"]
cardValues = ["Ace", 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, "J", "Q", "K"]
Values = [[1, 11], 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10]
for i in cardType:
    for j in cardValues:
        deckTypes.append(str(j) + " of " + str(i))
deck = dict(zip(deckTypes, Values*4))
z = 0
hand = []
while z < 5:
    card = random.choice(list(deck))
    handValue = deck[card]
    hand.append(card)
    z += 1
print(hand)
['7 of Spade', '4 of Clubs', '10 of Clubs', '4 of Spade', '4 of Hearts']