gpt4 book ai didi

python - 如何将字典中的值提取到数组中

转载 作者:行者123 更新时间:2023-11-28 22:40:57 24 4
gpt4 key购买 nike

spades = ['2S','3S','4S','5S','6S','7S','8S','9S','10S','JS','QS','KS','AS']
hearts = ['2H','3H','4H','5H','6H','7H','8H','9H','10H','JH','QH','KH','AH']
clubs = ['2C','3C','4C','5C','6C','7C','8C','9C','10C','JC','QC','KC','AC']
diamonds = ['2D','3D','4D','5D','6D','7D','8D','9D','10D','JD','QD','KD','AD']
allCards = spades + hearts + clubs + diamonds

import random
random.shuffle(allCards)

bot1 = [allCards.pop() for i in range(2)]
print(bot1)
cardVal = {'2S':1,'3S':2,'4S':3,'5S': 4,'6S':5,'7S':6,'8S':7,'9S':8,'10S':9,'JS':10,'QS':11,'KS':12,'AS':13,
'2H':1,'3H':2,'4H':3,'5H': 4,'6H':5,'7H':6,'8H':7,'9H':8,'10H':9,'JH':10,'QH':11,'KH':12,'AH':13,
'2C':1,'3C':2,'4C':3,'5C': 4,'6C':5,'7C':6,'8C':7,'9C':8,'10C':9,'JC':10,'QC':11,'KC':12,'AC':13,
'2D':1,'3D':2,'4D':3,'5D': 4,'6D':5,'7D':6,'8D':7,'9D':8,'10D':9,'JD':10,'QD':11,'KD':12,'AD':13}

for i in bot1:
print(cardVal[i])
bot1hand = [cardVal[i]]
print(bot1hand)

我想将 bot1 拥有的卡片值放在一个单独的数组中,但遇到了问题。我总是将两个值打印在不同的行上,数组 bot1hand 只存储这两个值的最后一个值。

例如:

>>> 
['AC', '5C']
13
4
[4]
>>>

最佳答案

你的问题就在这里:

for i in bot1:
print(cardVal[i])
bot1hand = [cardVal[i]]
print(bot1hand)

特别是这一行:

bot1hand = [cardVal[i]]

您不断地改写您的值(value)观,因为您实际上并没有正确地添加到您的列表中。实际上,您的 bot1hand 并未被视为列表。

您首先要做的是在循环之外将其初始化为列表:

bot1hand = []

然后在你的循环中,使用append方法:

bot1hand.append(cardVal[i])

所以你的最后一段代码应该是这样的:

bot1hand = []
for i in bot1:
print(cardVal[i])
bot1hand.append(cardVal[i])
print(bot1hand)

作为代码中的最后一个重构步骤,您实际上可以按照@NathanielFord 的建议进行操作,即使用理解(我看到您已经在代码中使用了它,因此您一定已经熟悉它)。我在这个答案中的那段代码现在可以简化为:

bot1hand = [cardVal[i] for i in bot1]

关于python - 如何将字典中的值提取到数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33158879/

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