【问题标题】:How to break into next iteration in while loop?如何在while循环中进入下一次迭代?
【发布时间】:2021-07-11 10:26:50
【问题描述】:

我有一段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 循环的下一次迭代?

【问题讨论】:

  • 那么 for 循环的目的是什么?
  • 你似乎对你的问题做了很大的改变。 while 循环发生了什么?
  • 抱歉我编辑后搞砸了

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


【解决方案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)

【讨论】:

    【解决方案2】:

    使用停止条件:

    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)
    

    【讨论】:

    • 这只会破坏最低的for循环,而不是直到while循环。
    • 只有我还是“for num2”在代码中看起来没有必要?
    • stop = True 仍然没有脱离for 循环。
    猜你喜欢
    • 2015-03-23
    • 2015-05-03
    • 2012-05-28
    • 2014-10-11
    • 2019-06-18
    • 2016-09-26
    • 2014-10-30
    • 2014-06-21
    • 2015-09-20
    相关资源
    最近更新 更多