繁体   English   中英

在以 Python 结束之后如何重新启动 for 循环?

[英]How can I restart a for loop after that it ended in Python?

我有以下功能:

def spell_checker(w):
     correzione = []
     limite = 2
     for word in frequenza():
         res = edit_distance(word.lower(), w)
        if word not in correzione:
              if res == 0: 
              correzione.append(w)
              break
        if res > 0 and res < limite: 
           correzione.append(word)

return correzione

因此,我需要做的是:当为循环结束,如果列表correzione是空的,我想增加LIMITE一个,并重新开始循环。

如果我将 limite += 1 放在循环中,它会在列表为空时增加,但只有在所有内容结束时它都为空时我才需要它。

它可能是这样的:

if len(correzione) == 0:
    limite += 1
for word in frequenza():
    #same loop as before

但这太多余了!

为了简单起见,您可以使用 while 循环继续工作,直到列表不为空:

    def spell_checker(w):
    correzione = []
    limite = 2
    while len(correzione) == 0:
        for word in frequenza():
            res = edit_distance(word.lower(), w)
            if word not in correzione:
                if res == 0: 
                    correzione.append(w)
                    break
            if res > 0 and res < limite: 
                correzione.append(word)
        if len(correzione) == 0:
            limite += 1
    return correzione

正如@Megalng 提出的那样,在这种情况下递归似乎很合理。 大概是这样的:

from edit_distance import edit_distance


MAX_LIMIT = 10


def frequenza():
    return ['first', 'second', 'third']


def spell_checker(w, limite=1):
    global MAX_LIMIT
    if limite > MAX_LIMIT:
        raise RuntimeError('Stack overflow!')

    correzione = []

    for word in frequenza():
        res = edit_distance(word.lower(), w)

        if word not in correzione:
            if res == 0:
                correzione.append(w)
                break

        if 0 < res < limite:
            correzione.append(word)

    if not correzione:
        return spell_checker(limite + 1)
    return correzione


def main():
    print(spell_checker('awordofmine'))


if __name__ == '__main__':
    main()

果然,你可以使用类而不是全局变量,或者以其他方式处理你的限制,比如 return None如果放弃是可以接受的。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM