在python中利用try..except来代替if..else的用法

(编辑:jimmy 日期: 2025/5/15 浏览:2)

在有些情况下,利用try…except来捕捉异常可以起到代替if…else的作用。

比如在判断一个链表是否存在环的leetcode题目中,初始代码是这样的

# Definition for singly-linked list.
# class ListNode(object):
#   def __init__(self, x):
#     self.val = x
#     self.next = None

class Solution(object):
  def hasCycle(self, head):
    """
    :type head: ListNode
    :rtype: bool
    """
    if head == None:
      return False
    slow =  head
    fast = head.next
    while(fast and slow!=fast):
      slow = slow.next
      if fast.next ==None:
        return False
      fast = fast.next.next
    return fast !=None

在 while循环内部,fast指针每次向前走两步,这时候我们就要判断fast的next指针是否为None,不然对fast.next再调用next指针的时候就会报异常,这个异常出现也反过来说明链表不存在环,就可以return False。

所以可以把while代码放到一个try …except中,一旦出现异常就return。这是一个比较好的思路,在以后写代码的时候可以考虑替换某些if…else语句减少不必要的判断,也使得代码变的更简洁。

修改后的代码

# Definition for singly-linked list.
# class ListNode(object):
#   def __init__(self, x):
#     self.val = x
#     self.next = None

class Solution(object):
  def hasCycle(self, head):
    """
    :type head: ListNode
    :rtype: bool
    """
    if head == None:
      return False
    slow =  head
    fast = head.next
    try:
      while(fast and slow!=fast):
        slow = slow.next
        fast = fast.next.next
      return fast !=None
    except:
      return False

以上这篇在python中利用try..except来代替if..else的用法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持。

一句话新闻

高通与谷歌联手!首款骁龙PC优化Chrome浏览器发布
高通和谷歌日前宣布,推出首次面向搭载骁龙的Windows PC的优化版Chrome浏览器。
在对骁龙X Elite参考设计的初步测试中,全新的Chrome浏览器在Speedometer 2.1基准测试中实现了显著的性能提升。
预计在2024年年中之前,搭载骁龙X Elite计算平台的PC将面世。该浏览器的提前问世,有助于骁龙PC问世就获得满血表现。
谷歌高级副总裁Hiroshi Lockheimer表示,此次与高通的合作将有助于确保Chrome用户在当前ARM兼容的PC上获得最佳的浏览体验。