正如标题所说:如何从列表中删除随机项? 我正在制作基于文本的游戏,我有一个列表,我想从中随机取一个项目,然后将其从列表中删除,如下所示:
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
感谢任何帮助。
答案 0 :(得分:6)
newcard
是列表(您使用random.sample(Deck, 1)
,它返回一个列表);使用方法:
Deck.remove(newcard[0])
或使用random.choice()
选择一个元素:
newcard = random.choice(Deck)