【问题标题】:For loop is skipping some stuff! PythonFor循环正在跳过一些东西! Python
【发布时间】:2012-11-29 22:23:06
【问题描述】:

我正在尝试运行此代码,以便它为列表的所有元素运行一个函数。此处出于说明目的,基本上应该打印:

'----------Possible Word:', possible_word

对于我列表中的所有项目。所以,如果我输入 ['p', 'r', 's'] 它将运行该打印 3 次,每个项目一个。我的代码在下面——当我运行它时,它只运行 p 和 s,而不是 r,这真的很奇怪。有什么想法吗?

def check_matches(input):
print 'Input:', input
for possible_word in input:
    print '----------Possible Word:', possible_word
    valid = True
    for real_word in word_dictionary:
        possible_word_list = list(possible_word)
        real_word_list = list(real_word)
        print possible_word_list
        print real_word_list
        number_of_characters_to_check = len(possible_word_list)
        for x in range(0, number_of_characters_to_check):
            print possible_word_list[x] + real_word_list[x]
            if (possible_word_list[x] != real_word_list[x]):
                valid = False
    if (valid == False):
        input.remove(possible_word)
print all_possible
return input

【问题讨论】:

  • 这个 .py 文件中还有其他函数和顶部的变量初始化,但我不想发布一个巨大的丑陋块,并认为这就是所有相关的。如果您认为我应该发布其余部分,请直接说。
  • 所以我们假设 word_dictionary 是全局列表,并且在之前定义?

标签: python loops skip


【解决方案1】:

当您运行input.remove(possible_word) 时,您正在更改您恰好正在迭代的列表的大小,这会导致奇怪的结果。一般来说,不要改变你正在迭代的任何东西。

更简洁的例子:

>>> lst = ['a', 'b', 'c']
>>> for el in lst:
    print el
    lst.remove(el)

a
c

【讨论】:

  • 啊,好吧-有道理。对不起,我错过了。
  • 不要从列表中删除无效项目,而是尝试创建一个新列表并添加有效的元素。这应该会给你想要的结果。
【解决方案2】:

乔恩·克莱门茨是对的。你通常不想做这样的事情。但是,我假设您对此有特定的需求。

答案很简单。换行

for possible_word in input:

到这一行

for possible_word in input[:]:

这将为您制作列表的副本以进行迭代。这样,当您删除一个项目时,它不会影响您的循环。

【讨论】:

  • 如果你提到这会复制输入会很好,这就是你可以这样做的原因。 :-)
猜你喜欢
  • 2015-05-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-08-16
  • 1970-01-01
  • 1970-01-01
  • 2021-10-11
  • 1970-01-01
相关资源
最近更新 更多