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]
>>>
答案 0 :(得分:3)
你的问题就在这里:
for i in bot1:
print(cardVal[i])
bot1hand = [cardVal[i]]
print(bot1hand)
特别是这一行:
bot1hand = [cardVal[i]]
您经常在写自己的价值观,因为您实际上没有正确地附加到您的列表中。实际上,您的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]
答案 1 :(得分:1)
您的for
循环是个问题。您可以尝试列出comprehension:
bot1hand = [cardVal[i] for i in bot1]
print(bot1hand)
(我假设print语句用于调试目的。)
列表理解处理实际为您构建列表的责任。