gpt4 book ai didi

python - 在循环中追加到列表会重置列表

转载 作者:行者123 更新时间:2023-12-01 09:29:20 27 4
gpt4 key购买 nike

这是我的代码:

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

我正在尝试附加到列表hand,但每次循环结束时它都会重置列表。所以我明白了:

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

怎样才能做到这样?

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

PS:这不是全部代码,但我试图使其尽可能清晰易懂

最佳答案

您错误地放置了的初始化。

<小时/>

使用当前代码,hand 设置为 [] 在每次迭代期间:

z = 0
while z < 5:
hand = [] # Executed during each iteration
hand.append(card)
print(hand)
z += 1

因此,每次迭代后,您都会得到一个只有 1 个元素的列表:

['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

现在,您可以看到元素在每次迭代时都正确附加到列表中:

['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 将包含您想要的以下列表:

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

关于python - 在循环中追加到列表会重置列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50103221/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com