我创建了一个字典,其中包含一组二十一点卡片中的不同卡片,我正在尝试编码。然而,在输出随机卡之后,我想将其从字典中删除,以便例如玩家在一轮中不接收两个Jack of Hearts。但是,我不想永久删除它,因为我希望它在新一轮回来时回来。这大致是我想要编写的代码(请注意我的代码中的字典包含所有卡片。)
#Create keys and values for cards
import random
dictCards = {'2 of Hearts': 2, '3 of Hearts': 3, '4 of Hearts': 4}
#Distribute cards
print(random.choice(list(dictCards.keys())))
del dictCards(random.choice(list(dictCards.keys())))
print(random.choice(list(dictCards.keys())))
任何帮助都将非常感激,如果可能的话,它可能是相对简单的术语,因为我是python的新手。请随时询问您是否要我清除任何内容。
答案 0 :(得分:1)
将它们放入列表并删除,尤其是在您每次拨打list(dictCards.keys())
时创建列表时:
import random
dictCards = {'2 of Hearts': 2, '3 of Hearts': 3, '4 of Hearts': 4}
cards = list(dictCards)
print(cards)
choice = random.choice(cards)
cards.remove(choice)
print(choice)
print(cards)
['4 of Hearts', '3 of Hearts', '2 of Hearts']
4 of Hearts
['3 of Hearts', '2 of Hearts']
如果你选择多张牌,你可能需要尝试/除以外:
for _ in range(5):
try:
choice = random.choice(cards)
cards.remove(choice)
print(choice)
except IndexError:
print("Sorry no more cards")
break
print(cards)
In [14]: paste
dictCards = {'2 of Hearts': 2, '3 of Hearts': 3, '4 of Hearts': 4}
cards = list(dictCards)
for _ in range(5):
try:
choice = random.choice(cards)
cards.remove(choice)
print(choice)
except IndexError:
print("Sorry no more cards")
break
print(cards)
## -- End pasted text --
4 of Hearts
3 of Hearts
2 of Hearts
Sorry no more cards
[]
答案 1 :(得分:0)
您需要创建字典的副本(使用dictCards.copy())来保存当前回合中未使用的卡片,并从该副本中删除使用过的卡片。
答案 2 :(得分:0)
您需要将删除的卡片添加到其他字典removed
,以便稍后再使用这些卡片。
演示:
>>> import random
>>> dictCards = {'2 of Hearts': 2, '3 of Hearts': 3, '4 of Hearts': 4}
>>> removed = {}
>>> while dictCards:
... key = random.choice(list(dictCards.keys()))
... print(key)
... removed[key]=dictCards[key]
... del dictCards[key]
...
4 of Hearts
2 of Hearts
3 of Hearts
>>> dictCards
{}
>>> removed
{'2 of Hearts': 2, '3 of Hearts': 3, '4 of Hearts': 4}
您现在可以将removed
分配回dictCards
。
答案 3 :(得分:0)
我建议使用set
s。 dict将在整个游戏中保持不变,作为卡值的查找表。变量stack
持有一轮牌。
import random
dictCards = {'2 of Hearts': 2, '3 of Hearts': 3, '4 of Hearts': 4}
# at the beginning of the round you create the card stack
stack = set(dictCards.keys())
# then you choose a single card (hence the 1) from the stack
chosenCard = random.sample(stack, 1)[0]
# this card has to be removed from the stack
stack.remove(chosenCard) # stack.discard(chosenCard) is also possible
print("stack:", stack)
print("chosen card:", chosenCard, "with value", dictCards[chosenCard])
输出
stack: {'3 of Hearts', '4 of Hearts'}
chosen card: 2 of Hearts with value 2