使用 while 循环查找下一个元素 python

Finding next element with while loop python

我坚持这个想法。我想打印紧跟在代词名词之后的动词,所以我正在迭代,直到循环找到一个动词。然后打印出来。但它似乎不仅给我打印了动词,还打印了其他元素。 知道我会出错吗?非常感谢

 points = [('I', 'PRON', 'nsubj'),
         ('don', 'AUX', 'aux'),
         ('t', 'PART', 'neg'),
         ('hope', 'VERB', 'ROOT'),
         ('that', 'SCONJ', 'mark'),
         ('the', 'DET', 'det'),
         ('salary', 'NOUN', 'nsubj'),
         ('will', 'AUX', 'aux'),
         ('change', 'VERB', 'ccomp'),
         ('.', 'PUNCT', 'punct')]

for i, (word, pos, dep) in enumerate(points):
    intermediate_list_sentences = []

    if pos == "PRON" or pos == "NOUN":
        iterate = 1
        while points[i+iterate][1] != "VERB":
            iterate+=1
            print(points[i+iterate][0])

OUTPOUT DESIRED => HOPE

要修正你的代码,你只需要 print 这个词 之后 你跳过了所有非动词词,而不是非动词词本身,即将 print 移出循环:

while points[i+iterate][1] != "VERB":
    iterate+=1
print(points[i+iterate][0])

或者,您可以从单词列表创建一个 iter 并使用两个嵌套的 for 循环迭代 相同的 迭代器:

it = iter(points)
for word, pos, dep in it:
    if pos in ("PRON", "NOUN"):
        print(word)
        for word2, pos2, _ in it:
            if pos2 == "VERB":
               print(word2)
               break

或者更简洁,使用next得到匹配的VERB:

it = iter(points)
for word, pos, dep in it:
    if pos in ("PRON", "NOUN"):
        verb = next((word2 for word2, pos2, _ in it if pos2 == "VERB"), None)
        print(word, verb)

输出:

I hope
salary change