【问题标题】:Try/exception command in while loop (Python)while循环中的尝试/异常命令(Python)
【发布时间】:2017-06-03 14:33:12
【问题描述】:

我正在尝试创建一个函数,用于在给定的 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..

【问题讨论】:

  • 我强烈建议您更具体地处理错误并添加一些反馈 - 目前您(或其他任何人)不可能看到究竟出了什么问题。
  • @jonrsharpe 感谢您的评论。我添加了一条评论以使我的目的更加明确。我在这里要做的是从数百个患者数据列表中挑选一批患者。我可以按顺序迭代批次,但这不起作用,因为一些患者的数据不起作用。我正在使用 try/exception 命令来处理该问题。抱歉,我对 python 比较陌生,所以我不确定这是否能回答你的问题。
  • 我没有问任何问题。我建议您进行更多调试 - 参见例如ericlippert.com/2014/03/05/how-to-debug-small-programs.
  • @jonrsharpe 感谢您的链接!

标签: python-3.x while-loop try-catch


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多