【问题标题】:Start a new iteration of a loop from a different function in the loop [python]从循环中的不同函数开始循环的新迭代[python]
【发布时间】:2014-04-07 19:53:09
【问题描述】:

如何在不使用 continue 或 break 的情况下开始下一个 i?

def function_in_main():
    if #something happens:
        #start new next iteration for the loop in the main function

def main():
    n = 1
    for i in range(len(alist)): 
        print ('step ', n)

        function_in_main()

        n += 1
main()

输出应该有点像:

第一步

#if 或直到某事发生

第二步

【问题讨论】:

  • 如果条件something happens不满足,循环是否应该中断?
  • @Hyperboreus 不应该
  • 让我换个说法:如果不满足条件something happens 会发生什么?

标签: python for-loop iteration


【解决方案1】:

当你的 if 语句为真时,让 function_in_main 返回。当它返回时,循环将继续进行下一次迭代,然后重新调用 function_in_main。

【讨论】:

    【解决方案2】:

    也许尝试引发异常:

    def function_in_main():
        if #something happens:
            raise Exception
    
    def main():
        n = 1
        for i in range(len(alist)): 
            print ('step ', n)
            try:
                x()
            except Exception:
                continue
    
            n += 1
    main()
    

    您可以指定或创建任何类型的异常。

    【讨论】:

      【解决方案3】:

      这是一个例子:

      def function_in_main(x):
          return x=='Whopee'         # will return True if equal else False
      
      def main():
          alist=['1','ready','Whopee']
          for i,item in enumerate(alist, 1): 
              print ('step {}, item: "{}" and {}'.format(i,item,function_in_main(item)))     
      
      main()
      

      打印:

      step 1, item: "1" and False
      step 2, item: "ready" and False
      step 3, item: "Whopee" and True
      

      注意使用enumerate 而不是手动保存计数器。

      【讨论】:

        【解决方案4】:

        确定您没有考虑 while 循环之类的东西吗?看到你在做什么有点困难......

        def your_function():
            #…do some work, do something to something else
            if something_is_true:
                return True
            else:
                return False
        
        def main():
            condition = True
            for i in range(len(your_list)):
                while condition:
                    print "Step: %d" % i
                    your_function()
        

        只有当your_function 返回 False 时,main 中的循环才会继续,否则它将停留在while 循环中。

        【讨论】:

          猜你喜欢
          • 2019-03-30
          • 1970-01-01
          • 2023-04-01
          • 2021-08-09
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2012-06-06
          • 2018-04-21
          相关资源
          最近更新 更多