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

yipeiwu_com5年前Python基础

本文实例讲述了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程序设计有所帮助。

相关文章

Python用for循环实现九九乘法表

下面通过一段代码给大家介绍python 使用for 循环实现九九乘法表,具体代码如下所示: #for 循环实现99乘法表 for i in range (1,10): for j...

python实现下载指定网址所有图片的方法

本文实例讲述了python实现下载指定网址所有图片的方法。分享给大家供大家参考。具体实现方法如下: #coding=utf-8 #download pictures of the u...

Python字符串中添加、插入特定字符的方法

Python字符串中添加、插入特定字符的方法

分析 我们将添加、插入、删除定义为: 添加 : 在字符串的后面或者前面添加字符或者字符串 插入 : 在字符串之间插入特定字符 在Python中,字符串是不可变的。所以无法直接删除、插入...

pybind11和numpy进行交互的方法

使用一个遵循buffer protocol的对象就可以和numpy交互了. 这个buffer_protocol要有哪些东西呢? 要有如下接口: struct buffer_i...

Python获取当前时间的方法

我有的时候写程序要用到当前时间,我就想用python去取当前的时间,虽然不是很难,但是老是忘记,用一次丢一次,为了能够更好的记住,我今天特意写下获取当前时间的方法,如果你觉的对你有用的话...