【问题标题】:How to handle KeyError exceptions properly via try / except?如何通过 try / except 正确处理 KeyError 异常?
【发布时间】:2017-05-20 08:05:18
【问题描述】:

为澄清而编辑:我正在尝试做一个学校练习,要求我构建接收元素和元组的函数,如果元素在元组中,它会反向返回其位置,即:

findInTupleA (1 , (1,2,3,1)

打印

[3, 0]

但如果元组中不存在该元素,则应发送KeyError 表示“元组中没有元素”。

def findInTupleA(elem,tuplo):
    lista_indices = []
    i = 0
    while i < len(tuplo):
        try:
            if tuplo[i] == elem:
                lista_indices.append(i)
            i = i + 1
        except KeyError:
            return "element not in tuple"

    if len(lista_indices)>=1:
        return lista_indices[::-1]
    else:
        return lista_indices

它仍然没有按预期工作,因为如果我给它元素 1 和元组 (2,3) 它返回一个空列表而不是关键错误,当我问的时候,reverse() 没有工作第二个if,不知道为什么。

附:如果您想评论我可以改进代码的方式,那就太棒了,对于断言部分也是如此!

【问题讨论】:

  • 为什么? ele in tuplo 不工作?
  • 请修正您的代码缩进。
  • 请修正缩进。编写的程序在语法上不正确。
  • 是什么让您认为这段代码中的任何内容都会导致您捕获 KeyError?
  • 你为什么期待KeyError?哦,是的:你确定你真的理解了练习的描述吗?您不应该在函数中引发异常并在函数调用之外捕获它吗?

标签: python exception assert


【解决方案1】:

我认为您的问题在于缩进。我认为你的目标是......

def findInTupleA(elem,tuplo):
    lista_indices = []
    i = 0
    while i < len(tuplo):
        try:
            if tuplo[i] == elem:
                lista_indices.append(i)
        except KeyError:
            return "element not in tuple"
        i = i + 1

    if len(lista_indices)>=1:
        return lista_indices[::-1]
    else:
        return lista_indices

【讨论】:

【解决方案2】:

如何检查元素index 是否在元组中。如果元素不存在,则在异常 ValueError 上返回 element not in tuple,如下所示:

def in_tuple(elem, tuplo):

    try:
        return tuplo.index(elem)
    except ValueError:
        return 'element not in tuple'

print in_tuple(1, (2, 3))

【讨论】:

  • 不是我想要的,但它的信息很好,效果很好,谢谢
【解决方案3】:

在我看来你误解了你的任务。我认为您不需要使用tryexcept 来捕获函数中的异常,而是应该自己引发异常(并且可能使用try/except在处理它的函数之外)。

尝试更多类似的方法,看看它是否满足您的需求:

def findInTupleA(elem,tuplo):
    lista_indices = []    
    i = 0
    while i < len(tuplo):
        if tuplo[i] == elem:
            lista_indices.append(i)
        i = i + 1

    if len(lista_indices) >= 1:
        return lista_indices
    else:
        raise IndexError("element not in tuple")

【讨论】:

  • 这成功了,如果我错了,请纠正我,我们正常运行循环然后检查输出列表是否为空,如果是,它会引发异常?
  • 是的,这正是这段代码的作用。您可以使用if elem in tuplo 在循环之前检查元素,但in 运算符与显式循环的作用基本相同,因此单独检查有点傻。我不确定IndexError 是在这种情况下提出的最合适的例外(ValueError 会更自然),但您应该符合为您的作业提供的规范。
猜你喜欢
  • 2017-04-03
  • 1970-01-01
  • 2016-09-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-09-10
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多