如何在while循环中进入下一次迭代?

时间:2021-04-16 11:33:24

标签: python python-3.x for-loop while-loop

我有一段while循环:

kw=[]
while len(kw)<count:
    for keyword in keywords:
        for ekw in ekw_embeddings:
            if np.inner(keyword,ekw)>threshold:
                kw.append(keyword)

这里在最后一个 if 条件之后如何在不检查下一个 for 循环的情况下转到 while 循环的下一次迭代?

2 个答案:

答案 0 :(得分:1)

您可以使用的一种技术是将 for 循环封装在函数中:

问题修改后更新:

def f(kw, keywords, ekw_embeddings):
    for keyword in keywords:
        for ekw in ekw_embeddings:
            if np.inner(keyword, ekw) > threshold:
                kw.append(keyword)
                return

kw = []
while condition:
    f(kw, keywords, ekw_embeddings)

答案 1 :(得分:0)

使用停止条件:

lst=[]; stop = False
while stop == False:
    for num in nums:
        for num2 in nums2:
            if condition:
               lst.append(num)
               stop = True
               break
        if stop == True:
            break

顺便说一句,不要使用 python 对象名称调用列表(或任何一般的东西)(因此不会将 dict 称为 dictlist 等...)

如果您可以使用函数:

def func(nums,nums2):
    lst=[]
    while condition:
        for num in nums:
            for num2 in nums2:
                if condition:
                   lst.append(num)
                   return lst

lst = func(nums,nums2)