欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

在python中利用try..except來(lái)代替if..else的用法

 更新時(shí)間:2019年12月19日 15:08:36   作者:很吵請(qǐng)安青爭(zhēng)  
今天小編就為大家分享一篇在python中利用try..except來(lái)代替if..else的用法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧

在有些情況下,利用try…except來(lái)捕捉異??梢云鸬酱鎖f…else的作用。

比如在判斷一個(gè)鏈表是否存在環(huán)的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循環(huán)內(nèi)部,fast指針每次向前走兩步,這時(shí)候我們就要判斷fast的next指針是否為None,不然對(duì)fast.next再調(diào)用next指針的時(shí)候就會(huì)報(bào)異常,這個(gè)異常出現(xiàn)也反過(guò)來(lái)說(shuō)明鏈表不存在環(huán),就可以return False。

所以可以把while代碼放到一個(gè)try …except中,一旦出現(xiàn)異常就return。這是一個(gè)比較好的思路,在以后寫(xiě)代碼的時(shí)候可以考慮替換某些if…else語(yǔ)句減少不必要的判斷,也使得代碼變的更簡(jiǎn)潔。

修改后的代碼

# 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來(lái)代替if..else的用法就是小編分享給大家的全部?jī)?nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。

相關(guān)文章

最新評(píng)論