在Python2中使用涉及列表的for循环进行append时出现的问题

在Python2中使用涉及列表的for循环进行append时出现的问题,append,Append,我是Python2的初学者,使用for循环的'append'命令有两个问题。 我试图让您运行这段代码,但它无法正常工作: def pole(): fish_pole = [] fish_elements = ['stick', 'liana', 'worm', 'bended needle'] pick_choice = raw_input() if pick_choice == "pick up": print "Good boy.

我是Python2的初学者,使用for循环的'append'命令有两个问题。 我试图让您运行这段代码,但它无法正常工作:

def pole():
    fish_pole = []
    fish_elements = ['stick', 'liana', 'worm', 'bended needle']

    pick_choice = raw_input()

    if pick_choice == "pick up":
            print "Good boy. You start picking up your 'tools'"

            for element in fish_elements:
                fish_pole.append(element)
                fish_elements.remove(element)
                print "You've found a %s and then" % element

            if not element in fish_elements:
                print "Ok you have the tools you need."
                print "Now you can go to the river."
                river()
     else:
        print "Come on. The sun is dying."
        pole()
好的,我的问题是:

  • 我不明白为什么它只为元素'stick'和元素'worm'打印“You'have find a%s and then”字符串

  • 如果我只写“if not fish_elements:”我就遇到了上面提到的第一个问题,另外还有一个问题:只要脚本打印完'stick'和'worm'的两个字符串,它就会直接转到'else'选项,并从头开始重新启动整个pole()定义


  • 请帮帮我。谢谢大家

    > p>由于您正在遍历FISHO元素的所有元素,可以考虑删除<代码>鱼尾元素。移除(元素)< /C> >,这可能是主要问题。

    for element in fish_elements: 
        fish_pole.append(element)
        print "You've found a %s and then" % element
    

    好吧,我想我误解了for循环的工作原理。在我看来,“for循环”应该附加每个元素,然后立即删除相同的元素,以便处理“fish_元素”列表中的后续元素。谢谢,我将尝试修复代码。问题是您在迭代序列时删除了代码。这是一种不好的做法,因为它将无法像你所希望的那样行事。我知道我“有点”迟到了,对此我很抱歉,但是……非常感谢!