附加到循环中的列表会重置列表

时间:2018-04-30 15:03:33

标签: 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.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:这不是全部代码,但我试图尽可能清楚地理解

2 个答案:

答案 0 :(得分:1)

您错放了hand的初始化。

使用您当前的代码,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']

答案 1 :(得分:0)

您的代码输出在此

['3 of Hearts']
['9 of Spade']
['3 of Spade']
['Ace of Diamonds']
['Q of Clubs']

但是当你移动hand = []并打印(hand)out while while循环时

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