本文實例講述了python實現的棧、隊列、文件目錄遍歷操作。分享給大家供大家參考,具體如下:
一、 棧與隊列
1、 棧 stack
特點:先進先出[可以抽象成竹筒中的豆子,先進去的后出來] 后來者居上
1
2
3
4
5
6
7
8
9
10
11
12
13
|
mystack = [] #壓棧[向棧中存數據] mystack.append( 1 ) print (mystack) mystack.append( 2 ) print (mystack) mystack.append( 3 ) print (mystack) #出棧[從棧中取數據] mystack.pop() print (mystack) mystack.pop() print (mystack) |
2、 隊列 queue
特點: 先進先出[可以抽象成一個平放的水管]
1
2
3
4
5
6
7
8
9
10
11
12
|
#導入數據結構的集合 import collections queue = collections.deque([ 1 , 2 , 3 , 4 , 5 ]) print (queue) #入隊[存數據] queue.append( 8 ) print (queue) queue.append( 9 ) print (queue) #取數據 print (queue.popleft()) print (queue) |
二、 目錄遍歷
1、 遞歸遍歷目錄
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
import os def diguigetalldir(path,suojin): # 如果文件夾中只有文件則返回 if os.path.isfile(path): return # 如果為空文件夾則返回 list1 = os.listdir(path) if len (list1) = = 0 : return # 遍歷list1列表 for item in list1: print ( ' ' * suojin, '%s' % item) path1 = os.path.join(path,item) if os.path.isdir(path1): diguigetalldir(path1, suojin + 4 ) # 遍歷當前目錄 diguigetalldir(os.getcwd(), 0 ) |
2、 棧模擬遞歸遍歷目錄
也稱為深度遍歷
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
import os def stackgetalldir(path): if not os.listdir(path): return liststack = [path] listsuojin = [ 0 ] print (liststack) while len (liststack) ! = 0 : path = liststack.pop() #路徑出棧 suojin = listsuojin.pop() #縮進空格個數出棧 print ( ' ' * suojin, os.path.basename(path)) if os.path.isdir(path): for i in os.listdir(path): #遍歷路徑下的全部文件 listsuojin.append(suojin + 4 ) liststack.append(os.path.join(path,i)) #文件名拼接成相對路徑后入棧 # 遍歷當前目錄 stackgetalldir(os.getcwd()) |
3、 隊列模擬遞歸遍歷目錄
也被稱為廣度遍歷
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
import os import collections def queuegetalldir(path = " " ): if not os.listdir(path): return queue = collections.deque() queue.append(path) while len (queue) ! = 0 : filepath = queue.popleft() filelist = os.listdir(filepath) #遍歷filepath路徑下的目錄 for filename in filelist: absfilepath = os.path.join(filepath,filename) #路徑拼接 if os.path.isdir(absfilepath): print ( "目錄:" ,filename) queue.append(absfilepath) else : print ( "文件:" ,filename) # 遍歷當前目錄 queuegetalldir(os.getcwd()) |
希望本文所述對大家python程序設計有所幫助。
原文鏈接:https://blog.csdn.net/lm_is_dc/article/details/80081904