歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> 用Python實現棧

用Python實現棧

日期:2017/3/1 10:05:28   编辑:Linux編程

這是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()

需要注意的就是對齊問題.

Copyright © Linux教程網 All Rights Reserved