我正在尝试创建一个功能,在CT扫描的给定目录中提取一批患者。一些患者'在图像分割过程中扫描失败,所以我循环遍历列表,直到找到"批号"成功分割的患者但是,当我运行它时,下面的代码无限循环。我不明白为什么要打破'不会终止循环。
任何想法都将非常感谢!:)
INPUT_FOLDER = "D:\CT\stage1\stage1"
patients = os.listdir(INPUT_FOLDER)
patients.sort()
#start, n_batch are given as parameters.
data = start #initialize index for list 'validation_patients'
valid_patient_list = [] #create an empty list for patient data with successful segmentation
while True: #iterate over variable 'data' until the list of valid patients is completed
try:
x = patients[data]
load_scan(INPUT_FOLDER + '\\' + x)
valid_patient_list.append(data)
if len(valid_patient_list) == n_batch: #escape while loop when the list length is equal to designated batch size
break
else: data += 1 #if the length of list is smaller than the desired batch number, go for the next patient
except IndexError:
data += 1 # go for the next data: do not add this one to the list
continue
#some more code below that deals with the valid_patient_list, but the loop runs infinitely..
答案 0 :(得分:0)
如果您在患者[数据]上得到IndexError,那是因为数据> = len(患者),索引超出范围错误,因此患者[data + 1]也会引发IndexErorr。
这会导致您的代码在引发和捕获异常之间进行无限循环,并且代码永远不会到达' break'一部分。