Python基础之栈与队列及递归目录

栈与队列
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")
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值