【问题标题】:Break loop execution for particular index from function call in python, then continue从python中的函数调用中中断特定索引的循环执行,然后继续
【发布时间】:2018-03-24 16:55:26
【问题描述】:

我的问题如下:

lst=[1,2,3,4,5]
lst_pass=[1,2,5]
count=0
flag=0
print "flag1"
print type(flag)


def fn1(lst_fn,j):
    if lst_fn[j] in lst_pass:
        print("pass")
        pass
    #if fail do not perform whatever is below fn call instead append index of for loop and check for next element

    else:
        flag=1
        return flag


print("code_prior")

for i in range(len(lst)):
    print lst[i]

    flag=fn1(lst,i)

    if flag!=1:
        print("code_after ")
        print lst[i] 

    flag=0

1) 如果通过,则只执行 fn 调用之后的任何内容 2) 在这种情况下,1,2 通过因此 code_after 应该为两者打印 3) j=3 code_after 不应该被打印,因为 3 不存在lst_pass;相反 for 循环应该执行 4 4)4 也不在 lst_pass 所以 code_after 不应该被打印,而是 for 循环应该执行 5 5) 5 在 lst_pass 所以理想情况下 code_after 应该被打印三次

上面的代码在粗略的标志方法中工作得很好,但是我必须按照同样的方法执行的代码很大,之后会调用很多 fns。有没有一种优雅的方式来做同样的事情?我正在使用 python 2.6。提前致谢。

【问题讨论】:

    标签: function for-loop python-2.6


    【解决方案1】:

    我可以从你的代码中了解到你试图循环遍历 lst 并检查它是否在 lst_pass 中,然后打印它们。

    只需将您的代码修改为:

    print("code_prior")
    for i in range(len(lst)):
      if lst[i] in lst_pass:
        print("code_after ")
        print lst[i] 
    

    无需为此逻辑声明单独的函数。

    【讨论】:

    • 我的代码实际上是用于验证的。我声明 fn 是为了消除代理成员。 print("code_after") 之后的代码很多,所以我一直在寻找一种比标志更好的方法来处理它。无论如何,谢谢!
    【解决方案2】:

    你可以试试这个:

    "code before"
    
    flag = fn1 (lst,i)
    
    if flag==1: 
        continue
    
    "code after"
    

    【讨论】:

    • 我想完全删除我的标志。我当然也可以继续使用,谢谢!
    猜你喜欢
    • 1970-01-01
    • 2012-10-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多