[英]How to pull out values from a dictionary into an array
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)
I want to put the values of the cards that bot1
owns in a separate array, but am running into an issue. 我想将bot1
拥有的卡的值放在一个单独的数组中,但是遇到了问题。 I always get the two values printed on separate lines and the array bot1hand
only stores the last value of the two. 我总是将两个值打印在单独的行上,而数组bot1hand
仅存储两个值的最后一个值。
For example: 例如:
>>>
['AC', '5C']
13
4
[4]
>>>
Your problem is right here: 您的问题就在这里:
for i in bot1:
print(cardVal[i])
bot1hand = [cardVal[i]]
print(bot1hand)
In particular this line: 特别是这一行:
bot1hand = [cardVal[i]]
You are constantly writing over your values because you are not actually properly appending to your list. 您一直在覆盖自己的价值观,因为您实际上没有正确地添加到列表中。 In fact, your bot1hand is not being considered a list. 实际上,您的bot1hand并未被视为列表。
What you want to do first is initialize it as a list outside of your loop: 您首先要做的是将其初始化为循环外的列表:
bot1hand = []
Then inside your loop, use the append method on it: 然后在循环中,在其上使用append方法:
bot1hand.append(cardVal[i])
So your final chunk of code should look like this: 因此,您最后的代码块应如下所示:
bot1hand = []
for i in bot1:
print(cardVal[i])
bot1hand.append(cardVal[i])
print(bot1hand)
As a final refactoring step in your code, you can actually do what @NathanielFord has suggested, is use a comprehension (which I see you already used in your code, so you must be already familiar with it). 作为代码中的最后一个重构步骤,您实际上可以执行@NathanielFord建议的操作,即使用理解(我已经看到您已经在代码中使用过,因此您必须已经熟悉它)。 That chunk of code I have in this answer can now be reduced to this: 现在我可以将这个答案中的那部分代码简化为:
bot1hand = [cardVal[i] for i in bot1]
Your for
loop is the problem. 您的for
循环就是问题所在。 You may want to try a list comprehension : 您可能想尝试列表理解 :
bot1hand = [cardVal[i] for i in bot1]
print(bot1hand)
(I'm assuming the print statement is for debugging purposes.) (我假设print语句用于调试目的。)
To list comprehension handles the responsibility of actually building the list for you. 列表理解处理为您实际构建列表的责任。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.