首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >while循环中的Try/exception命令(Python)

while循环中的Try/exception命令(Python)
EN

Stack Overflow用户
提问于 2017-06-03 22:33:13
回答 1查看 276关注 0票数 0

我正在尝试创建一个从给定的CT扫描目录中提取一批患者的函数。一些患者的扫描在图像分割过程中失败,所以我循环列表,直到我找到成功分割的患者的“批号”。然而,当我运行下面的代码时,它会无限循环。我不明白为什么'break‘没有终止循环。

任何想法都将不胜感激!:)

代码语言:javascript
复制
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..
EN

回答 1

Stack Overflow用户

发布于 2017-06-03 23:00:21

如果你在patientsdata上得到一个IndexError,这是因为data >= len(patients),一个索引超出范围的错误,所以patientsdata+1也会引发一个IndexErorr。

这会导致您的代码在引发和捕获异常之间陷入无限循环,并且代码永远不会到达“break”部分。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/44345005

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档