Python基礎之棧與佇列及遞迴目錄

Roc Huang發表於2020-10-09

棧與佇列

1 棧 stack

特點:先進後出 後來者居上


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

特點: 先進先出

#匯入資料結構的集合
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 遞迴遍歷目錄
import os

def getall(path, treeshow):
	filelist = os.listdir(path)
	treeshow += "	"
	for filename in filelist:
		#拼接絕對路徑
		filepath = os.path.join(path, filename)
		if os.path.isdir(filepath):
			print(treeshow,"目錄",filename)
			getall(filepath, treeshow)
		else:
			print(treeshow,"檔案",filename)
getall(r"d:\python\test","")
2 棧模擬遞迴遍歷目錄

也稱為深度遍歷

import os

def getAllDirDE(path):
	stack = []
	stack.append(path)
	#處理棧,當棧為空的時候結束迴圈
	while len(stack) != 0:
		#從棧裡取出資料
		dirPath = stack.pop()
		#目錄下所有檔案
		fileList = os.listdir(dirPath)
		for fileName in fileList:
			fileAbsPath = os.path.join(dirPath,fileName)
			if os.path.isdir(fileAbsPath):
				#是目錄就壓棧
				print("目錄:", fileName)
				stack.append(fileAbsPath)
			else:
				#列印普通檔案
				print("普通檔案:", fileName)
getAllDirED(r"/Users/zhangjiao/PycharmProjects/teaching")
3 佇列模擬遞迴遍歷目錄

也被稱為廣度遍歷

import os
import collections
def getAllDirQU(path):
	queue = collections.deque()
	#進隊
	queue.append(path)
	while len(queue) != 0:
		#出隊資料
		dirPath = queue.popleft()
		#找出所有的檔案
		fileList = os.listdir(dirPath)
		for fileName in fileList:
			#絕對路徑
			fileAbsPath = os.path.join(dirPath, fileName)
			#判斷是否是目錄,是目錄就進隊,不是就列印
			if os.path.isdir(fileAbsPath):
				print("目錄:", fileName)
				queue.append(fileAbsPath)
			else:
				print("普通檔案:", fileName)
getAllDirQU(r"/Users/zhangjiao/PycharmProjects/teaching")

相關文章