繁体   English   中英

Python:如何在 function 中正确实施引发异常

[英]Python : How to properly implement a raise an exception in a function

我正在尝试制作一个 function 来接收列表/数组并返回该序列中最大值的索引。 如果列表中存在非数值,则 function 应该引发异常。

def maxvalue(values):
    """
    Function that receives a list/array and returns the index of the maximum
    value in that sequence

    """    
    indices = []
    max_value = max(values)
    for i in range(len(values)):
        if type(i) not in (float, int): # raise an exception if the value is not float or integer
            raise TypeError("Only numberical values are allowed")
        if values[i] == max_value:
            indices.append(i)
    return indices

maxvalue([1, 1, 1.5, "e", 235.8, 9, 220, 220])

function 在收到包含浮点数和整数的列表时起作用,如果其中有字符串则不起作用。

当列表中存在 str 时,如何让 function 产生“TypeError("Only numberal values are allowed")”错误引用?

目前,它会产生“TypeError: '>' not supported between instances of 'str' and 'float'”

“比较”发生在最大 function 中,这会引发异常。

你应该在你的逻辑之前做所有的检查。

def maxvalue(values):
    """
    Function that receives a list/array and returns the index of the maximum
    value in that sequence

    """

    try:
        max_value = max(values)
    except TypeError:
        raise TypeError("Only numberical values are allowed")

    indices = []
    for idx, val in enumerate(values):
        if val == max_value:
            indices.append(idx)

    return indices

如您所见,我正在捕获 TypeError 并用不同的消息重新引发它。 还可以在 for 循环中使用枚举。

def maxvalue(values):
  indices = []
  print(values)
  int_values = []
  """the max function cannot fetch a max value with a string as part of the list so you can filter the list to get only integer values before you get max value"""
  for x in values: 
      if type(x)==int:
          int_values.append(x)

  max_value = max(int_values)

  for i in range(len(int_values)):
      if int_values[i] == max_value:
              indices.append(i)
  return indices

print(maxvalue([1, 1, 1.5, "e", 235.8, 9, 220, 220]))

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM