1

正如标题所说:如何从列表中删除随机项目?我正在制作基于文本的游戏,我有一个列表,我想从中随机取出一个项目,然后将其从列表中删除,如下所示:

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)

但是,当我尝试游戏中的“命令”“绘图”时,我总是会收到此输出和与列表相关的错误:

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

任何帮助表示赞赏。

4

1 回答 1

7

newcard是一个列表(您使用random.sample(Deck, 1),它返回一个列表);采用:

Deck.remove(newcard[0])

或用于random.choice()选择一个元素:

newcard = random.choice(Deck)
于 2012-12-28T21:31:46.233 回答