首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >从列表中删除随机项目

从列表中删除随机项目
EN

Stack Overflow用户
提问于 2012-12-29 05:27:25
回答 1查看 6.4K关注 0票数 0

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

代码语言:javascript
复制
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)

然而,当我尝试游戏中的‘命令’‘绘制’时,我总是得到这个输出和与列表相关的错误:

代码语言:javascript
复制
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

任何帮助都是非常感谢的。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2012-12-29 05:31:46

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

代码语言:javascript
复制
Deck.remove(newcard[0])

或者使用random.choice()拾取一个元素:

代码语言:javascript
复制
newcard = random.choice(Deck)
票数 7
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/14076013

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档