使用Python的判斷語句模擬三目運算
下面說的和三目運算有點相似,但又不一樣,實在不知道該如何擬定標題,先就是這個標題吧,大家都知道python中沒有三目運算,但是and/or有點類似三目運算:
and/or
單獨使用表示邏輯關系與和或,也可以組和使用,用法如下
and
and前后如果某一個值為假(False, '', [], {}, None…)則返回第一個假值 如果所有值都為真則返回最后一個真值
or
如果or任意一個值為真,則立刻返回這個值 如果所有值都為假,則or返回最后一個假值
例子
result = 'test' and True # result = True result = 'test' and 'ortest' # result = ortest result = False and 'ortest' # result = False result = '' and None # result = '' result = '' or "Hall" # result = Hall result = False or None # result = None result = 'test' or 'nottest' # result = test
使用單行if else 模擬三目運算
result if True / False else fresult if為真時候結果為result,為假的時候結果為fresult
result = 'test' if True else 'not test' # result = 'test' result = 'test' if False else 'not test' # result = 'not test'
相關文章
Python的collections模塊中的OrderedDict有序字典
字典是無序的,但是collections的OrderedDict類為我們提供了一個有序的字典結構,名副其實的Ordered+Dict,下面通過兩個例子來簡單了解下Python的collections模塊中的OrderedDict有序字典:2016-07-07
使用python+pandas讀寫xlsx格式中的數(shù)據(jù)
這篇文章主要介紹了使用python+pandas讀寫xlsx格式中的數(shù)據(jù),文章圍繞主題展開詳細的內(nèi)容介紹,具有一定的參考價值,感興趣的小伙伴可以參考一下2022-08-08
Python?Pandas?中的數(shù)據(jù)結構詳解
這篇文章主要介紹了Python?Pandas?中的數(shù)據(jù)結構詳解,Pandas有三種數(shù)據(jù)結構Series、DataFrame和Panel,文章圍繞主題展開更多相關內(nèi)容需要的小伙伴可以參考一下2022-06-06
Python中dictionary items()系列函數(shù)的用法實例
這篇文章主要介紹了Python中dictionary items()系列函數(shù)的用法,很實用的函數(shù),需要的朋友可以參考下2014-08-08

