我怎样才能在 For 中打印一些东西而不重复?

How can i print something in a For with no repeat?

我有以下问题:我在一个项目中使用 Yolo 来检测视频中的对象,当代码检测到一个对象时我需要一个警告但是代码发送了很多警告我只需要一次,我有明白你可以设置一个条件,这样打印就不会重复,但我不知道该怎么做,这是代码的一部分:

for detection in detections:
    if detection is not None:
        detection = rescale_boxes(detection, opt.img_size, RGBimg.shape[:2])
        for x1, y1, x2, y2, conf, cls_conf, cls_pred in detection:
            box_w = x2 - x1
            box_h = y2 - y1                       
            color = [int(c) for c in colors[int(cls_pred)]]
            print("there is {}".format(classes[int(cls_pred)]))
            frame = cv2.rectangle(frame, (x1, y1 + box_h), (x2, y1), color, 5)
            cv2.putText(frame, classes[int(cls_pred)], (x1, y1), cv2.FONT_HERSHEY_SIMPLEX, 1, color, 5) 
            cv2.putText(frame, str("%.2f" % float(conf)), (x2, y2 - box_h), cv2.FONT_HERSHEY_SIMPLEX, 0.5,color, 5)

我用这个解决了这个问题:

x=0
def add():
    global x
    x=x+1

我不知道这是否是解决问题的最佳方法,但它确实有效。

for detection in detections:
        if detection is not None:
            detection = rescale_boxes(detection, opt.img_size, RGBimg.shape[:2])
            for x1, y1, x2, y2, conf, cls_conf, cls_pred in detection:
                                 
                if x<=0:
                    add()
                    print("Se detectó posible {}".format(classes[int(cls_pred)]))
                box_w = x2 - x1
                box_h = y2 - y1                       
                color = [int(c) for c in colors[int(cls_pred)]]
                frame = cv2.rectangle(frame, (x1, y1 + box_h), (x2, y1), color, 5)
                cv2.putText(frame, classes[int(cls_pred)], (x1, y1), cv2.FONT_HERSHEY_SIMPLEX, 1, color, 5)# Nombre de la clase detectada
                cv2.putText(frame, str("%.2f" % float(conf)), (x2, y2 - box_h), cv2.FONT_HERSHEY_SIMPLEX, 0.5,color, 5) # Certeza de prediccion de la clase

如果你只想在第一次迭代时做一些事情(例如打印),你可以只设置一个标志:

first = True
for .........
            # somewhere inside your loop
            if first:
                # print or whatever
                first = False