The example in this paper describes how Python implements the stack. Share to everyone for your reference. The implementation method is as follows:
#!/usr/bin/env python #定义一个列表来模拟栈 stack = [] #进栈, the Append () function of the invocation list is added to the end of the list, strip () No parameters are stripped-down spaces def pushit (): Stack.append ( Raw_input (' Enter new string: '). Strip ()) #出栈, using the Pop () function Def popit (): If Len (stack) = = 0:print ' cannot pop from an E Mpty stack! ' Else:print ' Removed [', Stack.pop (), '] ' #编历栈 def viewstack (): print stack #CMDs是字典的使用 CMDs = {' U ': pushit, ' o ': PO Pit, ' V ': viewstack} #pr为提示字符 def showmenu (): PR = "" "P (U) SH p (O) p (v) iew (Q) uit Enter choice:" "while True:while true:try: #先用strip () Remove the space and convert the first character to lowercase choice = raw_input (pr). Strip () [0].lower () Except (Eoferror, Keyboardinterrupt, indexerror): choice = ' q ' print ' \nyou picked: [%s] '% choice If choice not in ' uovq ': print ' Invalid option, try again ' else:break #CMDs [] corresponds to the corresponding v from the dictionary according to the choice of the input Alue, for example, enter U, get value as Pushit from the dictionary, execute Pushit () into the stack operation if choice = = ' Q ': Break Cmds[choice] () #判断是否是从本文件进入 instead of being called if __name__ == ' __main__ ': ShowMenu ()
Hopefully this article will help you with Python programming.