简体   繁体   English

嵌套循环中仅打印一次

[英]Print only once in nested loop

I am modeling a particle moving through different layers, and once it moves through the layer I want it to print a few things. 我正在对一个穿过不同层的粒子建模,一旦它穿过层,我希望它打印一些东西。 My problem is the particle can move back into the previous layer and come out again, which triggers it to print again, I do not want this. 我的问题是粒子可以移回上一层并再次出现,从而触发它再次打印,我不希望这样。

while math.sqrt((pho.pos.x)*(pho.pos.x)+(pho.pos.y)*(pho.pos.y)+(pho.pos.z)*(pho.pos.z))<10:
    x=random.uniform(-j,j)
    y=random.uniform(-j,j)
    z=random.uniform(-j,j)
    step=(x,y,z)
    t=t+dt
    pho.pos=pho.pos+step
    print 'Step Number', t
    rate(speed)
    d=math.sqrt((pho.pos.x)*(pho.pos.x)+(pho.pos.y)*(pho.pos.y)+(pho.pos.z)*(pho.pos.z))
    '''if d>10:
        print pho.pos 
        print d 
        print 'Out of Layer 1 in',t,'steps!'
        break
    else:
        pass'''
d=math.sqrt((pho.pos.x)*(pho.pos.x)+(pho.pos.y)*(pho.pos.y)+(pho.pos.z)*(pho.pos.z))
print pho.pos
print d
print 'Out of Layer 1 in',t,'steps!'

The part I don't want repeating is the last three print statements, I have tried break statements but this code is a nested loop, and when it gets re-looped it starts over before the break. 我不想重复的部分是最后三个print语句,我尝试了break语句,但是此代码是嵌套循环,当它重新循环时,它将在中断之前重新开始。

On whatever class pho is, make a property called printed or something and initialize it to False . 在任何pho类上,都创建一个名为printed或something的属性,并将其初始化为False Then, set it to True when printing for the first time, and say 然后,在第一次打印时将其设置为True,然后说

if d > 10 and not pho.printed

instead of just if d > 10 . 而不是仅仅if d > 10

Try something like this. 尝试这样的事情。 Your code I think was all supposed to be part of the while loop. 认为您的代码都应该是while循环的一部分。 If not, move the out_of_layer to before the next outer loop. 如果不是,请将out_of_layer移至下一个外部循环之前。

out_of_layer = False  

while math.sqrt((pho.pos.x)*(pho.pos.x)+(pho.pos.y)*(pho.pos.y)+(pho.pos.z)*(pho.pos.z))<10:
    x=random.uniform(-j,j)

    ... blah blah stuff you already know about ...

    d=math.sqrt((pho.pos.x)*(pho.pos.x)+(pho.pos.y)*(pho.pos.y)+(pho.pos.z)*(pho.pos.z))
    if not out_of_layer:
        print pho.pos
        print d
        print 'Out of Layer 1 in',t,'steps!'
        out_of_layer = True

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM