1

これはおそらく悪い設計の結果ですが、これで終わりです。この問題を説明する方法がよくわかりませんでした。

そのため、単語のリストを反復処理するコードがあります。(このリストは変更されません。) 次に、一連の基準に応じて、コードが特定の単語を解析して結合し、それらを新しいリストに格納します。各単語を一度に 1 つずつ取得するマスター ループは、コードが適合すると判断したものをスキップする必要があります。たとえば、次のようになります。

マスターループの単語リスト:

ListA = [リンゴ、バナナ、ペンギン]

マスター ループ内で、私のコードがリンゴとバナナを一緒に属すると判断したとしましょう。

ListB = [りんごバナナ、ペンギン]

ここで、Master Loop に bananna をスキップさせたいと思います。バナナが何か他のものとペアになっているかどうかをチェックする必要はありません。したがって、continue ステートメントを使用します。これが問題です。いくつの単語がペアになるかわかりません。そのため、1 つまたは 3 つの継続が必要になる可能性があります。必要な回数だけ継続を実行するために考えることができる唯一の方法は、ループを使用することです...しかし、継続はそれが含まれるループに影響を与えるため、問題が発生します。

マスターループを必要なだけ継続させる方法はありますか? おそらく私は単純なものを見逃しています。ご協力いただきありがとうございます。

編集

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 に答える