Skip to main content
 首页 » 编程设计

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

2025年05月04日8zlslch

我已经创建了一个字典,其中包含我正在尝试编写的二十一点游戏的一副纸牌中的不同纸牌。但是,在输出随机卡之后,我想将其从字典中删除,例如,玩家不会在一轮中收到两张红心 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 
[]