Python Lesson 32-Queue

Queue: Meet the characteristics --> First in, first out, similar to buying tickets and security in our lives

【note】

For queues: Python has specific functions for encapsulation, and the deque function in the collections module can get a queue object;

Steps:

Step 1: Import the collections module

Step 2: collections.deque() --> return the queue object

Step 3: Use the queue object to call its deposit and retrieval functions to complete the requirements

Demonstrate the characteristics of data access in the queue: first in, first out

import collections

# Get the queue object: deque()
queue=collections.deque()print(queue,type(queue))

# Adding data to the queue: Queue operation
queue.append('A')print(queue)

queue.append('B')print(queue)

queue.append('C')print(queue)

# Pop the data in the queue: Dequeue operation
obj=queue.popleft()print('pop up:'+obj)

obj=queue.popleft()print('pop up:'+obj)

obj=queue.popleft()print('pop up:'+obj)'''
Simulate the use of queue structure to achieve breadth traversal of traversal directories
'''
import collections,os
# Custom function: realize the operation of traversing multiple directory levels(Breadth traversal)
def getAllFileQU(path):
 # Get a queue
 queue=collections.deque()
 # Join path data
 queue.append(path)
 # As long as there is data in the queue, the loop continues
 whilelen(queue)!=0:
  file_path=queue.popleft()
  # Get file_All words in path(Files, subdirectories)
  files_list=os.listdir(file_path)
  # Loop processing file_each element in the list
  for file in files_list:
   # Restore its absolute path value
   fileAbsPath=os.path.join(file_path,file)
   # Determine whether it is a file or a directory, the operation is the same as the depth traversal
   if os.path.isfile(fileAbsPath):print('file:'+file)else:print('table of Contents:'+file)
    queue.append(fileAbsPath)

path=r'test.txt'getAllFileQU(path)

In order to better understand the characteristics of stack and queue access data:

We wrote code operations for depth traversal and breadth traversal,

From this, we know that you can use the requirement of traversing multi-level directories without using recursive operations.

The advantage of this is: more memory resources are saved

Recommended Posts

Python Lesson 32-Queue
python queue Queue
Python Lesson 32-Stack
Python Lesson 37-Module
Python multithreading
Python CookBook
Python FAQ
Python3 dictionary
Python3 module
python (you-get)
Python string
Python basics
Python descriptor
Python exec
Python notes
CentOS + Python3.6+
Python advanced (1)
Python decorator
Python IO
Python multithreading
Python3 list
Python multitasking-coroutine
python introduction
07. Python3 functions
Python basics 3
Python multitasking-threads
python sys.stdout
python operator
Python entry-3
Centos 7.5 python3.6
Python string
Python basics 4
Python basics 5