gpt4 book ai didi

python - Python随机输出一个字典条目,如何临时删除?

转载 作者:太空宇宙 更新时间:2023-11-04 05:56:19 24 4
gpt4 key购买 nike

我已经创建了一个字典,其中包含我正在尝试编写的二十一点游戏的一副纸牌中的不同纸牌。但是,在输出随机卡之后,我想将其从字典中删除,例如,玩家不会在一轮中收到两张红心 jack 。但是,我不想永久删除它,因为我希望它在有新一轮时返回。这大致是我要编写的代码(请注意,我代码中的字典包含所有卡片)。

#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 的新手。请随时询问您是否要我清理任何东西。

最佳答案

将它们放入列表中并删除,尤其是在每次调用 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
[]

关于python - Python随机输出一个字典条目,如何临时删除?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27582276/

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