首页 > 解决方案 > 用于查找对象并在找到对象后停止的控制流

问题描述

我有一个相机装置,我在其中初始化阶段,然后需要移动相机并找到可检测到对象的范围。我无法预测物体将在哪里。如果相机没有检测到物体,我会增加相机阶段并再次查看。当我找到开始可检测到对象的位置时,我将当前相机位置附加到列表中。我在整个范围内重复这一点。我想做的是停止不必要的尝试,一旦它不再在视野内,即一旦它不再被发现。我想到了一个可能如下所示的列表: y_list = [100,150,200,250,300,...500] 并且我无法弄清楚如何检查列表是否在 for 循环的几次迭代中停止增长。我想使用另一个列表来显示何时检测到对象但没有

y_list_flags = [0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0]

代码

y_list = []
len_y = len(y_list)

for i in list(range(1,70):
    my_obj = obj_present()#returns True if object detected, False otherwise
    if my_obj:
        y_list.append(current_cam_position)
        move_cam_stage()
    elif my_obj not True:
        move_cam_stage()

期望的输出

y_list = [100,150,200,250,300, 350,400,450,500,550,600] # list stops growing when object not found and test has stopped

或者

y_list = [100,150,200,250,300, 350,400,450,500,550,600] # list stops growing when object not found and test has stopped a few attempts after drop is no longer found

标签: pythonnested-loopscontrol-flow

解决方案


和是move_cam_stageobj_present函数。

当再次找不到对象时,循环中断和列表停止增长。

代码:

def move_cam_stage():
    print("move cam stage")

def obj_present(i):
    y_list_flags = [0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0]
    return y_list_flags[i] == 1

y_list = []
for i in range(1,70):
    my_obj = obj_present(i)#returns True if object detected, False otherwise
    if my_obj:
        y_list.append(50 + 50*i)
        move_cam_stage()
    else:
        if len(y_list)>1:
            break
print(y_list)

结果:

move cam stage
move cam stage
move cam stage
move cam stage
move cam stage
move cam stage
move cam stage
move cam stage
move cam stage
move cam stage
move cam stage
[450, 500, 550, 600, 650, 700, 750, 800, 850, 900, 950]

推荐阅读