栈与队列
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")