简体   繁体   English

从列表中删除随机项目

[英]Removing a random item from a list

As the title says: how to you remove a random item from a list? 如标题所述:如何从列表中删除随机项目? I am making text based game, and I have a list in which I want to randomly take an item from and then remove it from the list, as seen below: 我正在制作基于文本的游戏,并且我有一个列表,我希望从中随机取出一个物品,然后从列表中将其删除,如下所示:

Deck = ['Lumina, Lighsworn Summoner', 'Lumina, Lighsworn Summoner', 'Judgment Dragon', 'Judgment Dragon', 'Judgment Dragon', 'Jain, Lightsworn Paladin', 'Ehren, Lightsworn Monk', 'Lyla, Lightsworn Sorceress', 'Lyla, Lightsworn Sorceress', 'Ryko, Lighsworn Hunter', 'Ryko, Lighsworn Hunter', 'Ryko, Lighsworn Hunter', 'Celestia, Lightsworn Angel', 'Aurkus, Lightsworn Druid', 'Garoth, Lightsworn Warrior', 'Garoth, Lightsworn Warrior', 'Lightray Gearfried', 'Lightray Gearfried', 'Lightray Gearfried', 'Lightray Daedalus', 'Lightray Daedalus', 'Lightray Daedalus', 'Lightray Diabolos', 'Lightray Diabolos', 'Lightray Diabolos', 'Sephylon, the Ultimate Timelord', 'Sephylon, the Ultimate Timelord', 'Sephylon, the Ultimate Timelord', 'Card Trooper', 'Card Trooper', 'Honest', 'Gorz the Emissary of Darkness', 'Necro Gardna', 'Necro Gardna', 'Necro Gardna', 'Charge of the Light Brigade', 'Solar Recharge', 'Solar Recharge', 'Solar Recharge', 'Beckoning Light', 'Beckoning Light']
loop = 1
while loop == 1:
    option = raw_input()
    if option == 'draw':
        newcard = random.sample(Deck, 1)
        print newcard
        Deck.remove(newcard)

However, when I try the in-game 'command' "draw", I always get this output and list-related error: 但是,当我尝试游戏中的“命令”“绘制”时,总是会得到以下输出和与列表相关的错误:

draw
['Judgment Dragon']
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "YGOGame.py", line 183, in <module>
    Deck.remove(newcard)
ValueError: list.remove(x): x not in list

Any help is appreciated. 任何帮助表示赞赏。

newcard is a list (you used random.sample(Deck, 1) , which returns a list); newcard是一个列表 (您使用了random.sample(Deck, 1) ,它返回一个列表); use: 采用:

Deck.remove(newcard[0])

or use random.choice() to pick one element: 或使用random.choice()选择一个元素:

newcard = random.choice(Deck)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM