List remove x not in list while trying to make pokemon game

2024-05-23 17:36:13 发布

您现在位置:Python中文网/ 问答频道 /正文

尽管该行现在是多余的,但是在运行几个迭代之后,应该从原始列表中删除self.y的行会引发“Valueerror:列表.删除(x) x不在列表中。我现在不知道我做错了什么。在

from random import sample, choice


class Selection(object):


    def __init__(self):

        self.pokemon_list = [
            'Blastoise', 'Charizard', 'Venasaur',   
            'Artiquno', 'Moltress', 'Zapdos', 
        ]

        self.x = sample(self.pokemon_list, 3)

        print """
    CONGRATULATIONS TRAINER, YOU HAVE BEEN GIVEN %s,
    YOUR JOURNEY BEGINS NOW! PROCEED WISELY OR DIE.
    """ % (self.x)


    def gary_pok(self):

        for self.z in self.x:

            if self.z == "Blastoise":
                self.y = 'Venasaur'
                **self.pokemon_list.remove(self.y)
                print self.pokemon_list**
            elif self.z == "Charizard":
                self.y = 'Blastoise'
                print self.pokemon_list.remove(self.y)
            elif self.z == "Venasaur":
                self.y = 'Charizard'
                print self.pokemon_list.remove(self.y)
            else:
                self.y = choice(self.pokemon_list)
                print self.pokemon_list.remove(self.y)

        print "Gary's pokemons:{}, Nidoqueen and Archanine.".format(self.y)

bah = Selection()
bah.gary_pok()      

Tags: sampleself列表defremovelistprintchoice
1条回答
网友
1楼 · 发布于 2024-05-23 17:36:13

循环时,无法从列表中删除项。 因为,当循环第一次发生时,它将从您的列表中移除项,当循环进行第二次迭代时,它希望移除已经移除的项。在

enter image description here

在打印Artiquioni之后,Charizard被删除,然后在下一次迭代中,Charizard不在列表中

相关问题 更多 >