如果所谓的声明,忽略后,即使条件已经满足

问题描述:

我有一个简单的if语句在我的代码如果所谓的声明,忽略后,即使条件已经满足

if len(bootstrap_node_list_recieved_no_dups) >= min_node_to_complete_boot_strap: 
    print "recieved required nodes" 

基本上我想知道是否有足够的节点,我只希望这发生一次,如代码仍然会继续运行,因此当前每次运行if语句都会如我所料。

有没有一种方法来编写代码,以便if语句运行,但是一旦它完成后永远不会再运行?由于输入不是常数,因此需要>=

我希望这很清楚,因为它有点难以描述。

更新,

我试图实施的建议,但我得到的错误

UnboundLocalError: local variable 'flag' referenced before assignment 
下面

全码:

flag = False 

def number_of_duplicates_in_list(): 
    number_recieved = len(bootstrap_node_list_recieved) 
    bootstrap_node_list_recieved_before = len(bootstrap_node_list_recieved_no_dups) 

    " this method works in O(n^2) time and is thus very slow on large lists" 
    for i in bootstrap_node_list_recieved: 
     if i not in bootstrap_node_list_recieved_no_dups: 
      bootstrap_node_list_recieved_no_dups.append(i) 
    assert len(bootstrap_node_list_recieved_no_dups) >= bootstrap_node_list_recieved_before 
    if len(bootstrap_node_list_recieved_no_dups) >= min_node_to_complete_boot_strap and flag is False: 
     print "recieved required nodes" 
     flag = True 
+3

'如果hasnt_run_yet和len(...):hasnt_run_yet = False; ...'...? – deceze

你可以有改变时,有些萎靡不振的变量首先触发if语句。下面的代码是一个最小的例子,它只会打印一次“触发”语句,即使所有大于3的数字都会触发语句,如果该标志也没有被检查。

flag = False 

for x in xrange(10): 
    if x > 3 and flag is False: 
     print 'Triggered' 
     flag = True 

    # Do something else 

如果你想在一个函数中做到这一点,你需要将标志初始化移入函数中。请注意,重新运行功能将复位标志:

def test_func(): 
    flag = False 
    for x in xrange(10): 
     if x > 3 and flag is False: 
      print 'Triggered' 
      flag = True 

    # Do something else 

test_func() 

为了能够运行一次函数多次,但只能触发if声明并更改标志,则需要该标志链接到函数调用。这样做的一个简单的方法是通过并在每次调用返回的标志:

flag = False 

def test_func(flag): 
    for x in xrange(10): 
     if x > 3 and flag is False: 
      print 'Triggered' 
      flag = True 

    # Do something else 
    return flag 

flag = test_func(flag) 
flag = test_func(flag) 

这里,标志调用时定义的功能之外,并传递到每一个功能。如果没有被触发,它会通过而不会改变。如果被触发,它会被改变,并且它的状态会被传回到函数之外。

其他方法可以定义一个global变量或建立一个类作为对象变量并通过self访问它。

+0

谢谢我已经尝试过这种方法,但不断得到UnboundLocalError:赋值前引用的局部变量'flag' – Rich

+0

Iv根据您的要求用两种解决方案更新了答案 – Wokpak

定义flag在number_of_duplicates_in_list内为全局。否则,你只能阅读它。