使用列表推导调用的函数自定义异常处理

时间:2017-06-02 04:03:59

标签: python exception-handling

我有一个函数,它接受一个列表或numpy整数数组,表示一些值的间隔,然后将这个列表分成两个几乎相等的子区间。使用列表推导会多次调用此函数。

截至目前,如果输入间隔少于四个元素,则该函数返回None,None。如何编写自定义异常来捕获间隔少于四个元素的任何实例,提醒用户,不返回任何内容?

import numpy as np
from math import floor

def split_interval(hparam_interval, overlap=0.25):
    """
    Divides the original hyperparameter interval into two subintervals with
    a given amount of overlap.

    Keyword arguments:
    hparam_interval -- original hyperparameter interval to be searched over
    overlap -- percent overlap between the resulting subintervals
    """
    hparam_interval.sort()

    seq_len = len(hparam_interval)
    if seq_len < 4:
        return None, None

    halfway = seq_len//2
    seq_overlap = floor(seq_len * overlap)//2

    subseq_low = hparam_interval[:halfway+seq_overlap]
    subseq_hi = hparam_interval[halfway-seq_overlap:]
    return subseq_low, subseq_hi

x = np.arange(0,9).tolist()
y = np.arange(11, 20).tolist()
z = np.arange(2).tolist()

intervals = [x, y, z]
lo_intervals, hi_intervals = zip(*[split_interval(x) for x in intervals])

print(lo_intervals) # ([0, 1, 2, 3, 4], [11, 12, 13, 14, 15], None)

理想情况下,我会将第一个return语句替换为异常,并且在任何列表少于四个元素的情况下不返回任何内容。

这是我的第一次:

class IntervalDivisionError(Exception):
    pass

def split_interval(hparam_interval, overlap=0.25):
    """
    Divides the original hyperparameter interval into two subintervals with
    a given amount of overlap.

    Keyword arguments:
    hparam_interval -- original hyperparameter interval to be searched over
    overlap -- percent overlap between the resulting subintervals
    """
    hparam_interval.sort()
    seq_len = len(hparam_interval)

    try:
        if seq_len < 4:
            raise IntervalDivisionError("Sequence must be at least length 4!")
    except:
        halfway = seq_len//2
        seq_overlap = floor(seq_len * overlap)//2

        subseq_low = hparam_interval[:halfway+seq_overlap]
        subseq_hi = hparam_interval[halfway-seq_overlap:]
        return subseq_low, subseq_hi

x = np.arange(0,9).tolist()
y = np.arange(11, 20).tolist()
z = np.arange(2).tolist()

intervals2 = [x, y, z]

lo_intervals2, hi_intervals2 = zip(*[split_interval(x) for x in intervals2])

"""
Runs with:

TypeError                                 Traceback (most recent call last)
<ipython-input-24-dd4f490d2b95> in <module>()
     31 intervals2 = [x, y, z]
     32
---> 33 lo_intervals2, hi_intervals2 = zip(*[split_interval(x) for x in 
intervals2])

TypeError: zip argument #1 must support iteration
"""

我知道我离解决方案很远。我仍然试图了解异常是如何工作的。感谢您的帮助!

0 个答案:

没有答案