如何在for循环中更改迭代?

2024-04-24 07:37:19 发布

您现在位置:Python中文网/ 问答频道 /正文

file = ['Tool','Cool','Pool']
word = 'Cool'
guesses = ['T','P']
for i in range(len(file)):
    if len(file[i]) == len(word):
        for j in range(len(file[i])):
            print(file[i][j])
            for k in range(len(guesses)):
                print(guesses[k])
                if file[i][j] == guesses[k]:
                    i + 1

在我的代码段中,我遇到了移动到列表中的下一项file的问题。当file[0][0] == 'T'guesses[0] == 'T'发生时,我想转到文件列表中的下一项。我认为i + 1是合适的,但似乎不起作用。你知道吗


Tags: 文件in列表forlenif代码段range
1条回答
网友
1楼 · 发布于 2024-04-24 07:37:19

这里要做的是使用continue,但由于有几个嵌套循环,因此无法正常工作,因此我们可以使用助手方法将其减少为一个for循环,然后使用continue

def find_any(what, where):
    for that in what:
       if that in where:
           return True
    return False

file = ['Tool','Cool','Pool']
word = 'Cool'
guesses = ['T','P']
for i in range(len(file)):
    if len(file[i]) == len(word) and find_any(guesses, file[i]):
        continue # This will skip to the next file
    # Do things with file[i] here

相关问题 更多 >