欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Python实现的栈、队列、文件目录遍历操作示例

程序员文章站 2023-08-15 10:25:12
本文实例讲述了python实现的栈、队列、文件目录遍历操作。分享给大家供大家参考,具体如下: 一、 栈与队列 1、 栈 stack 特点:先进先出[可以抽象成竹筒中的...

本文实例讲述了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 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、 栈模拟递归遍历目录

也称为深度遍历

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、 队列模拟递归遍历目录

也被称为广度遍历

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相关内容感兴趣的读者可查看本站专题:《python数据结构与算法教程》、《python加密解密算法与技巧总结》、《python编码操作技巧总结》、《python函数使用技巧总结》、《python字符串操作技巧汇总》及《python入门与进阶经典教程

希望本文所述对大家python程序设计有所帮助。