我可以跳过封闭循环的不确定步骤吗? (蟒蛇)

时间:2010-08-05 18:28:48

标签: python continue

这可能是设计糟糕的结果,但事实如此。我不太清楚如何解释这个问题。

所以我有代码迭代一个单词列表。 (此列表不会更改。)然后,代码会根据一组条件将某些单词解析并组合在一起,并将它们存储在新列表中。主循环,每次一个字一个,然后需要跳过代码决定的拟合。例如:

主循环的单词列表:

ListA = [apple,banana,penguin]

在主循环中,假设我的代码决定了apple和bananna属于一起,所以

ListB = [apple banana,penguin]

现在我想让Master Loop跳过bananna,它不需要检查是否看到香蕉与其他东西配对。所以我会使用continue语句。这是问题所在。我不知道会有多少单词最终配对。所以我最终可能需要一个继续,或者三个继续。我可以想到的唯一方法是根据需要继续运行多次是使用循环...但这会产生问题,因为继续会影响它所在的​​循环。

有没有办法让主循环根据需要连续多次?也许我错过了一些简单的事情。谢谢你的帮助。

修改

word_list = ["apple", "banana", "penguin"]    #word_list will be arbitrary in practice
phrase_length = 0    #phrase_length is the amount of times I would like to skip

for k, word in enumerate(word_list):
    #I would like to have the continues run here, before any of the below code        

    #the code down here decides what to pair in a forward fashion
    #so it starts from apple and looks ahead to see if something fits with it
    #continues in this manner till it comes up with the longest possible pairing
    #phrase_length is then set equal to the amount of words used make the pairing

如果必须执行香蕉代码,也会浪费相当多的计算时间,也可以从那里检查。这就是为什么我想跳过香蕉检查。

3 个答案:

答案 0 :(得分:0)

您可以尝试使用itertools模块,特别是dropwhile函数。

答案 1 :(得分:0)

我错过了什么吗?

word_list = ["apple", "banana", "penguin"]
skip_list = {}

for word in self.word_list:
    if word in skip_list:
        continue

    # Do word-pairing logic; if word paired, skip_list[word] = 1

可能不是编程效率最高,但至少简洁明了。

答案 2 :(得分:0)

您可以显式使用迭代器的next方法。

>>> l = [1, 2, 3, 4, 5, 6]
>>> l_iter = iter(l)
>>> for n in l_iter:
      if n==2:
        print '{0}+{1}+{2}'.format(n, l_iter.next(), l_iter.next())
      else:
        print n
1
2+3+4
5
6
编辑:是的,当与枚举结合使用时会变得混乱。想到的另一个选择:将函数写为生成器,如:

def combined_words(word_list):
  combined_word = ""
  for k, word in enumerate(word_list):
    combined_word += k
    if next_word_can_be_paired:
      pass
    else: # next word can't be paired
      yield combined_word
      combined_word = ""
  if combined_word:
    yield combined_word # just in case anything is left over

然后拨打list(combined_words(word_list))以获取新列表。

相关问题