1

这可能是糟糕设计的结果,但它就是这样。我不太确定如何解释这个问题。

所以我有迭代单词列表的代码。(这个列表不会改变。)然后代码会根据一组标准解析和组合某些单词,将它们存储在一个新列表中。主循环一次只取一个单词,然后需要跳过代码认为合适的内容。例如:

主循环的单词列表:

ListA = [苹果、香蕉、企鹅]

在主循环中,假设我的代码决定苹果和香蕉属于一起,所以

ListB = [苹果香蕉,企鹅]

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

如果它也必须执行香蕉的代码,并且还要从那里向前检查,那将浪费大量的计算时间。这就是为什么我想跳过香蕉检查。

4

3 回答 3

0

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

于 2010-08-05T18:35:33.830 回答
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

可能不是编程效率最高的,但至少清晰简洁。

于 2010-08-05T18:51:46.423 回答
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))以获取新列表。

于 2010-08-05T18:52:57.173 回答