我們都知道Python 中else的基本用法是在條件控制語句中的if...elif...else...,但是else 還有兩個其它的用途,一是用於循環的結尾,另一個是用在錯誤處理的try 中。這原本是 Python 的標準語法,但由於和大部分其它程式語言的習慣不太一樣,致使人們有意或無意地忽略了這些用法。另外,對於這些用法是否符合 0×00 The Zen of Python 的原則以及該不該廣泛使用也存在著許多爭議。例如在我看到的兩本書裡(Effective Python VS Write Idiomatic Python),兩位作者就分別對其持有截然不同的態度。
迴圈中的 else
跟在迴圈後面的 else 語句只有在當迴圈內沒出現 break,也就是正常迴圈完成時才會執行。首先我們來看一個插入排序法的例子:
from random import randrange def insertion_sort(seq): if len(seq) 1: return seq _sorted = seq[:1] for i in seq[1:]: inserted = False for j in range(len(_sorted)): if i _sorted[j]: _sorted = [*_sorted[:j], i, *_sorted[j:]] inserted = True break if not inserted: _sorted.append(i) return _sorted print(insertion_sort([randrange(1, 100) for i in range(10)])) [8, 12, 12, 34, 38, 68, 72, 78, 84, 90]
在這個例子中,對已排序的_sorted 元素逐一與i 進行比較,若i比已排序的所有元素都大,則只能排在已排序清單的最後。這時我們就需要一個額外的狀態變數inserted 來標記完成遍歷循環還是中途被break,在這種情況下,我們可以用else 來取代這個狀態變數:
def insertion_sort(seq): if len(seq) 1: return seq _sorted = seq[:1] for i in seq[1:]: for j in range(len(_sorted)): if i _sorted[j]: _sorted = [*_sorted[:j], i, *_sorted[j:]] break else: _sorted.append(i) return _sorted print(insertion_sort([randrange(1, 100) for i in range(10)])) [1, 10, 27, 32, 32, 43, 50, 55, 80, 94]
我認為這是一個非常酷的做法!不過要注意的是,除了break 可以觸發後面的else 語句,沒有循環的時候也會:
#while False: print("Will never print!") else: print("Loop failed!") Loop failed!##錯誤捕捉中的else#try...except...else...finally 流程控制語法用於捕捉可能出現的異常並進行相應的處理,其中except 用於捕捉try 語句中出現的錯誤;而else 則用於處理沒有出現錯誤的情況;finally 負責try 語句的」善後工作「 ,無論如何都會執行。可以透過一個簡單的範例來展示:
def pide(x, y): try: result = x / y except ZeropisionError: print("pision by 0!") else: print("result = {}".format(result)) finally: print("pide finished!") pide(5,2) print("*"*20) pide(5,0)
result = 2.5 pide finished! ******************** pision by 0! pide finished!
def pide(x, y): result = None try: result = x / y except ZeropisionError: print("pision by 0!") if result is not None: print("result = {}".format(result)) print("pide finished!") pide(5,2) print("*"*20) pide(5,0)#####################
result = 2.5 pide finished! ******************** pision by 0! pide finished!################################################################################ ####總結######有人覺得else 的這些用法違反直覺或是implicit 而非explicit,不值得提倡。但我覺得這種」判決「需要依賴具體的應用場景以及我們對 Python 的理解,並非一定要對新人友好的語法才算是 explicit 的。當然也不建議在所有地方都使用這個語法,for/while...else 最大的缺點在於else 是需要與for/file 對齊的,如果是多層嵌套或者循環體太長的情況,就非常不適合用else(回想一下游標卡尺的梗就知道了:P)。只有在一些簡短的循環控制語句中,我們透過 else 擺脫一些累贅的狀態變量,這才是最 Pythonic 的應用場景! ######更多Python中的else的詳細介紹相關文章請關注PHP中文網! ######

ForhandlinglargedatasetsinPython,useNumPyarraysforbetterperformance.1)NumPyarraysarememory-efficientandfasterfornumericaloperations.2)Avoidunnecessarytypeconversions.3)Leveragevectorizationforreducedtimecomplexity.4)Managememoryusagewithefficientdata

Inpython,ListSusedynamicMemoryAllocationWithOver-Asalose,而alenumpyArraySallaySallocateFixedMemory.1)listssallocatemoremoremoremorythanneededinentientary上,respizeTized.2)numpyarsallaysallaysallocateAllocateAllocateAlcocateExactMemoryForements,OfferingPrediCtableSageButlessemageButlesseflextlessibility。

Inpython,YouCansspecthedatatAtatatPeyFelemereModeRernSpant.1)Usenpynernrump.1)Usenpynyp.dloatp.dloatp.ploatm64,formor professisconsiscontrolatatypes。

NumPyisessentialfornumericalcomputinginPythonduetoitsspeed,memoryefficiency,andcomprehensivemathematicalfunctions.1)It'sfastbecauseitperformsoperationsinC.2)NumPyarraysaremorememory-efficientthanPythonlists.3)Itoffersawiderangeofmathematicaloperation

Contiguousmemoryallocationiscrucialforarraysbecauseitallowsforefficientandfastelementaccess.1)Itenablesconstanttimeaccess,O(1),duetodirectaddresscalculation.2)Itimprovescacheefficiencybyallowingmultipleelementfetchespercacheline.3)Itsimplifiesmemorym

SlicingaPythonlistisdoneusingthesyntaxlist[start:stop:step].Here'showitworks:1)Startistheindexofthefirstelementtoinclude.2)Stopistheindexofthefirstelementtoexclude.3)Stepistheincrementbetweenelements.It'susefulforextractingportionsoflistsandcanuseneg

numpyallowsforvariousoperationsonArrays:1)basicarithmeticlikeaddition,減法,乘法和division; 2)evationAperationssuchasmatrixmultiplication; 3)element-wiseOperations wiseOperationswithOutexpliitloops; 4)

Arresinpython,尤其是Throughnumpyandpandas,weessentialFordataAnalysis,offeringSpeedAndeffied.1)NumpyArseNable efflaysenable efficefliceHandlingAtaSetSetSetSetSetSetSetSetSetSetSetsetSetSetSetSetsopplexoperationslikemovingaverages.2)


熱AI工具

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

Video Face Swap
使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

熱工具

Dreamweaver Mac版
視覺化網頁開發工具

MinGW - Minimalist GNU for Windows
這個專案正在遷移到osdn.net/projects/mingw的過程中,你可以繼續在那裡關注我們。 MinGW:GNU編譯器集合(GCC)的本機Windows移植版本,可自由分發的導入函式庫和用於建置本機Windows應用程式的頭檔;包括對MSVC執行時間的擴展,以支援C99功能。 MinGW的所有軟體都可以在64位元Windows平台上運作。

PhpStorm Mac 版本
最新(2018.2.1 )專業的PHP整合開發工具

SublimeText3 英文版
推薦:為Win版本,支援程式碼提示!

SAP NetWeaver Server Adapter for Eclipse
將Eclipse與SAP NetWeaver應用伺服器整合。