Python 堆疊
堆疊是一個後進先出(LIFO)的資料結構. 堆疊這個資料結構可以用來處理大部分具有後進先出的特性的程式流.
在堆疊中, push 和pop 是常用術語:
push: 意思是把一個物件入棧.
pop: 意思是把一個物件出棧.
下面是一個由Python 實現的簡單的堆疊結構:
stack = [] # 初始化一个列表数据类型对象, 作为一个栈 def pushit(): # 定义一个入栈方法 stack.append(raw_input('Enter New String: ').strip()) # 提示输入一个入栈的 String 对象, 调用 Str.strip() 保证输入的 String 值不包含多余的空格 def popit(): # 定义一个出栈方法 if len(stack) == 0: print "Cannot pop from an empty stack!" else: print 'Remove [', `stack.pop()`, ']' # 使用反单引号(` `)来代替 repr(), 把 String 的值用引号扩起来, 而不仅显示 String 的值 def viewstack(): # 定义一个显示堆栈中的内容的方法 print stack CMDs = {'u':pushit, 'o':popit, 'v':viewstack} # 定义一个 Dict 类型对象, 将字符映射到相应的 function .可以通过输入字符来执行相应的操作 def showmenu(): # 定义一个操作菜单提示方法 pr = """ p(U)sh p(O)p (V)iew (Q)uit Enter choice: """ while True: while True: try: choice = raw_input(pr).strip()[0].lower() # Str.strip() 去除 String 对象前后的多余空格 # Str.lower() 将多有输入转化为小写, 便于后期的统一判断 # 输入 ^D(EOF, 产生一个 EOFError 异常) # 输入 ^C(中断退出, 产生一个 keyboardInterrupt 异常) except (EOFError, KeyboardInterrupt, IndexError): choice = 'q' print '\nYou picked: [%s]' % choice if choice not in 'uovq': print 'Invalid option, try again' else: break if choice == 'q': break CMDs[choice]() # 获取 Dict 中字符对应的 functionName, 实现函数调用 if __name__ == '__main__': showmenu()
NOTE: 在堆疊主要資料結構中應用了List 資料型別物件的容器和可變等特性, 表現在List.append() 和List.pop() 這兩個清單類型內建函數的呼叫.
感謝閱讀,希望能幫助大家,謝謝大家對本站的支持!
更多Python 資料結構之堆疊實例程式碼相關文章請關注PHP中文網!

pythonlistscanStoryDatatepe,ArrayModulearRaysStoreOneType,and numpyArraySareSareAraysareSareAraysareSareComputations.1)列出sareversArversAtileButlessMemory-Felide.2)arraymoduleareareMogeMogeNareSaremogeNormogeNoreSoustAta.3)

WhenyouattempttostoreavalueofthewrongdatatypeinaPythonarray,you'llencounteraTypeError.Thisisduetothearraymodule'sstricttypeenforcement,whichrequiresallelementstobeofthesametypeasspecifiedbythetypecode.Forperformancereasons,arraysaremoreefficientthanl

pythonlistsarepartofthestAndArdLibrary,herilearRaysarenot.listsarebuilt-In,多功能,和Rused ForStoringCollections,而EasaraySaraySaraySaraysaraySaraySaraysaraySaraysarrayModuleandleandleandlesscommonlyusedDduetolimitedFunctionalityFunctionalityFunctionality。

ThescriptisrunningwiththewrongPythonversionduetoincorrectdefaultinterpretersettings.Tofixthis:1)CheckthedefaultPythonversionusingpython--versionorpython3--version.2)Usevirtualenvironmentsbycreatingonewithpython3.9-mvenvmyenv,activatingit,andverifying

Pythonarrayssupportvariousoperations:1)Slicingextractssubsets,2)Appending/Extendingaddselements,3)Insertingplaceselementsatspecificpositions,4)Removingdeleteselements,5)Sorting/Reversingchangesorder,and6)Listcomprehensionscreatenewlistsbasedonexistin

NumPyarraysareessentialforapplicationsrequiringefficientnumericalcomputationsanddatamanipulation.Theyarecrucialindatascience,machinelearning,physics,engineering,andfinanceduetotheirabilitytohandlelarge-scaledataefficiently.Forexample,infinancialanaly

useanArray.ArarayoveralistinpythonwhendeAlingwithHomoGeneData,performance-Caliticalcode,orinterfacingwithccode.1)同質性data:arraysSaveMemorywithTypedElements.2)績效code-performance-calitialcode-calliginal-clitical-clitical-calligation-Critical-Code:Arraysofferferbetterperbetterperperformanceformanceformancefornallancefornalumericalical.3)

不,notalllistoperationsareSupportedByArrays,andviceversa.1)arraysdonotsupportdynamicoperationslikeappendorinsertwithoutresizing,wheremactsperformance.2)listssdonotguaranteeconecontanttanttanttanttanttanttanttanttanttimecomplecomecomplecomecomecomecomecomecomplecomectacccesslectaccesslecrectaccesslerikearraysodo。


熱AI工具

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

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

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

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

熱門文章

熱工具

VSCode Windows 64位元 下載
微軟推出的免費、功能強大的一款IDE編輯器

SublimeText3 Linux新版
SublimeText3 Linux最新版

記事本++7.3.1
好用且免費的程式碼編輯器

SublimeText3漢化版
中文版,非常好用

mPDF
mPDF是一個PHP庫,可以從UTF-8編碼的HTML產生PDF檔案。原作者Ian Back編寫mPDF以從他的網站上「即時」輸出PDF文件,並處理不同的語言。與原始腳本如HTML2FPDF相比,它的速度較慢,並且在使用Unicode字體時產生的檔案較大,但支援CSS樣式等,並進行了大量增強。支援幾乎所有語言,包括RTL(阿拉伯語和希伯來語)和CJK(中日韓)。支援嵌套的區塊級元素(如P、DIV),