1. 栈
1.1 示例
#!/usr/bin/env python
# -*- codinfg:utf-8 -*-
'''
@author: Jeff LEE
@file: .py
@time: 2018-07-20 9:19
@desc: 先入后出
'''
queue = []
#入栈
print('************入栈*************')
queue.append('A')
print(queue)
queue.append('B')
print(queue)
queue.append('C')
print(queue)
#出栈
print('************出栈*************')
queue.pop()
print(queue)
queue.pop()
print(queue)
queue.pop()
print(queue)
1.2 运行结果
2. 队列
2.1 示例
#!/usr/bin/env python
# -*- codinfg:utf-8 -*-
'''
@author: Jeff LEE
@file: 队列.py
@time: 2018-07-20 9:27
@desc: 先入先出
'''
import collections
queue =collections.deque()
#入栈
print('************入栈*************')
queue.append('A')
print(queue)
queue.append('B')
print(queue)
queue.append('C')
print(queue)
#出栈
print('************出栈*************')
queue.popleft()
print(queue)
queue.popleft()
print(queue)
queue.popleft()
print(queue)
2.2 运行结果
3. 案例
3.1 递归遍历目录
3.1.1 概念
递归就是一个函数在它的函数体内调用它自身。执行递归函数将反复调用其自身,每调用一次就进入新的一层。递归函数必须有结束条件。
当函数在一直递推,直到遇到墙后返回,这个墙就是结束条件。
所以递归要有两个要素,结束条件与递推关系
3.1.2 示例
#!/usr/bin/env python
# -*- codinfg:utf-8 -*-
'''
@author: Jeff LEE
@file: 递归遍历目录.py
@time: 2018-07-20 9:31
@desc:
'''
import os
def getAllDir(path,sp=''):
#获取目录
filesList=os.listdir(path)
for fileName in filesList:
#文件的绝对路径
fileAbsPath = os.path.join(path,fileName)
#判断是否为文件
if os.path.isfile(fileAbsPath):
print(sp+ '普通文件:',fileAbsPath)
else:
print(sp+ '目录:', fileAbsPath)
sp += ' '
getAllDir(fileAbsPath,sp)
getAllDir(r'D:\testproject\core')
3.1.3 运行结果
3.2栈方式递归目录
3.2.1 示例
#!/usr/bin/env python
# -*- codinfg:utf-8 -*-
'''
@author: Jeff LEE
@file: 栈方式遍历目录.py
@time: 2018-07-20 10:16
@desc:
'''
import os
def getAllDir(path,sp=''):
stack=[]
stack.append(path)
#当栈为空时,目录遍历完
while len(stack) !=0:
#从栈取数据
fileDir=stack.pop()
filesList = os.listdir(fileDir)
for fileName in filesList:
# 文件的绝对路径
fileAbsPath = os.path.join(fileDir, fileName)
# 判断是否为文件
if os.path.isfile(fileAbsPath):
print('普通文件:', fileName)
else:
print('目录:', fileName)
stack.append(fileAbsPath)
getAllDir(r'D:\testproject\core')
3.2.2 运行结果
3.3 队列方式递归目录
3.3.1 示例
#!/usr/bin/env python
# -*- codinfg:utf-8 -*-
'''
@author: Jeff LEE
@file: 队列方式遍历目录.py
@time: 2018-07-20 14:41
@desc:
'''
import os
import collections
def getAllDir(path,sp=''):
queue =collections.deque()
queue.append(path)
#当栈为空时,目录遍历完
while len(queue) !=0:
#从栈取数据
fileDir=queue.popleft()
filesList = os.listdir(fileDir)
for fileName in filesList:
# 文件的绝对路径
fileAbsPath = os.path.join(fileDir, fileName)
# 判断是否为文件
if os.path.isfile(fileAbsPath):
print('普通文件:', fileName)
else:
print('目录:', fileName)
queue.append(fileAbsPath)
getAllDir(r'D:\testproject\core')
3.3.2 运行结果