如何在 python 中的前一个循环中转到列表的下一个单词?

How can you go to the next word of a list on the previous loop in python?

要转到循环中的下一个单词,您只需使用继续功能。

例如

a = ['a', 'b', 'c', 'd']
for word in a:
    continue

但是如果代码是这样的:

a = ['a', 'b', 'c', 'd']
for word in a:
    for word2 in word:
        continue

continue 函数适用于第二个循环,但我想要一些适用于第一个循环并同时写入第二个循环的东西。

使用当前索引帮助您导航到循环位置之外。枚举内置函数非常适合这个。

a = ['a', 'b', 'c', 'd']
l = len(a)
for i, word in enumerate(a):
    nexti = i + 1
    nextword = a[nexti] if nexti <= l else None
    ...

您可以使用一个变量来判断是否需要继续第二次:

a = ['a', 'b', 'c', 'd']
for word in a:
    for word2 in word:
        do_continue = true # Defining the variable
        continue
    if do_continue:
        continue

您可以从内部循环中断并使用 else 来确定外部循环是否应该继续。

a = ['aaaaxaaaa', 'bbbbbb', 'cccccxccc', 'ddddxddd']
for word in a:
    for letter in word:
        at_end=False
        if (letter == 'x'): break
        print(letter)
    else:    # only called at end of loop if no break
        at_end = True
    if (at_end == False): continue  # inner loop exited early
    print(word)