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

yipeiwu_com6年前Python基础

在有些情况下,利用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的用法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

Centos5.x下升级python到python2.7版本教程

首先到官网下载python2.7.3版本,编译安装 复制代码 代码如下: $wget http://www.python.org/ftp/python/2.7.3/Python-2.7....

详细介绍pandas的DataFrame的append方法使用

详细介绍pandas的DataFrame的append方法使用

官方文档介绍链接:append方法介绍 DataFrame.append(other, ignore_index=False, verify_integrity=False, sort=...

Django项目中使用JWT的实现代码

Django项目中使用JWT的实现代码

1.requiremwnts: Django版本:2.2 python版本:3.6 djangorestframework版本:3.1 djangorestframew...

Python 多核并行计算的示例代码

Python 多核并行计算的示例代码

以前写点小程序其实根本不在乎并行,单核跑跑也没什么问题,而且我的电脑也只有双核四个超线程(下面就统称核好了),觉得去折腾并行没啥意义(除非在做IO密集型任务)。然后自从用上了32核128...

PyQt5每天必学之工具提示功能

PyQt5每天必学之工具提示功能

本文将教会我们如何使用PyQt5控件的工具提示功能。 #!/usr/bin/python3 # -*- coding: utf-8 -*- """ PyQt5 教程 这个例子显示...