python的栈在哪个库_Python实现栈的方法
本文實例講述了Python實現棧的方法。分享給大家供大家參考。具體實現方法如下:
#!/usr/bin/env python
#定義一個列表來模擬棧
stack = []
#進棧,調用列表的append()函數加到列表的末尾,strip()沒有參數是去掉首尾的空格
def pushit():
stack.append(raw_input('Enter new string: ').strip())
#出棧,用到了pop()函數
def popit():
if len(stack) == 0:
print 'Cannot pop from an empty stack!'
else:
print 'Removed [', stack.pop(), ']'
#編歷棧
def viewstack():
print stack
#CMDs是字典的使用
CMDs = {'u': pushit, 'o': popit, 'v': viewstack}
#pr為提示字符
def showmenu():
pr = """
p(U)sh
p(O)p
(V)iew
(Q)uit
Enter choice: """
while True:
while True:
try:
#先用strip()去掉空格,再把第一個字符轉換成小寫的
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[]根據輸入的choice從字典中對應相應的value,比如說輸入u,從字典中得到value為pushit,執行pushit()進棧操作
if choice == 'q':
break
CMDs[choice]()
#判斷是否是從本文件進入,而不是被調用
if __name__ == '__main__':
showmenu()
總結
以上是生活随笔為你收集整理的python的栈在哪个库_Python实现栈的方法的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 小米拒绝权限_小米手机MIUI12真有那
- 下一篇: websocket python爬虫_p