栈和队列

it2022-05-27  68

#后进先出格式 #进栈 stack=[] stack.append('A') stack.append('B') stack.append('C') print(stack) # #出栈 stack.pop() stack.pop() stack.pop() print(stack) 实例 #栈思想解决指定目录遍历文件问题 ''' 1.以列表的形式创建栈,并将目录放入栈中, stack=[path] 2.进行循环条件判断:如果该栈不为空,就执行循环条件,就退出循环,结束程序 3.不为空就取出栈中的目录,从最后一个开始取(遵循先进后出原则,也就是下面的遍历中,先添加的最后被取出,也就是每次会从子目录列表中的最后一个目录开始遍历) dir=stack.pop() 3.使用os.listdir(dir)以列表的形式把该目录下的所有文件名和目录名进行保存后遍历该列表,获得每个子文件名(或目录名) for file in listdir(dir): 4.通过os.path.join获取目录下的子文件或目录的路径, file_path=os.path.join(dir,file) 5.判断该file是否为目录 if os.path.isdir(file_path): 5.如果是目录就添加到栈中 stack.append(file_path) 6.如果是文件就打印显示文件名,最终会把栈中的所有目录都遍历完以取出所有的文件(但是会从每级目录的最后一个目录开始遍历,所以列出的文件顺序是反的) print(file) 解决思想: 就是通过栈将需要查询的目录下的所有子目录都以列表的形式保存,然后中最后一个开始取出栈中的每个目录,进行遍历,把文件逐个打印出来 解决的几个问题: 1.通过判断栈是否为空,解决所有文件都查找出来后结束程序的问题 2.通过栈保存目录,以先进后出思想,挨个遍历并取出栈中目录得到文件的一连串行为,达到搜寻指定目录下所有文件的目的 ''' #开始操作 import os def get_file(path): stack = [path] while stack: dir = stack.pop() for file in os.listdir(dir): file_path = os.path.join(dir, file) if os.path.isdir(file_path): stack.append(file_path) else: print(file) get_file('d:\\学习\\')

queue

#先进先出 #队列:排队 queue=[] #入队 queue.insert(0,'A') print(queue) queue.insert(0,'B') print(queue) queue.insert(0,'C') print(queue) #出队 queue.pop() print(queue) queue.pop() print(queue) queue.pop() print(queue) #应用(思路类似栈) import os def get_file(path): #创建队列并保存目录路径 queue=[path] #取出队列中的目录 while queue: dir=queue.pop() for file in os.listdir(dir): file_path=os.path.join(dir,file) if os.path.isdir(file_path): queue.insert(0,file_path) else: print(file) get_file('d:\\学习\\')

转载于:https://www.cnblogs.com/endmoon/p/9675993.html


最新回复(0)