[
183
]
•
They have strict ordering of elements
•
They support the append operation efficiently
They tend to be slow, however, if you are inserting elements anywhere but the end of
the list (especially so if it's the beginning of the list). As we discussed in the section on
sets, they are also slow for checking if an element exists in the list, and by extension,
searching. Storing data in a sorted order or reordering the data can also be inefficient.
Let's look at the three types of containers provided by the Python
queue
module.
FIFO queues
FIFO stands for
First In First Out
and represents the most commonly understood
definition of the word "queue". Imagine a line of people standing in line at a bank or
cash register. The first person to enter the line gets served first, the second person in
line gets served second, and if a new person desires service, they join the end of the
line and wait their turn.
The Python
Queue
class is just like that. It is typically used as a sort of communication
medium when one or more objects is producing data and one or more other objects is
consuming the data in some way, probably at a different rate. Think of a messaging
application that is receiving messages from the network, but can only display one
message at a time to the user. The other messages can be buffered in a queue in the
order they are received. FIFO queues are utilized a lot in such concurrent applications.
(We'll talk more about concurrency in
Chapter 12
,
Testing Object-oriented Programs
.)
The
Queue
class is a good choice when you don't need to access any data inside
the data structure except the next object to be consumed. Using a list for this would
be less efficient because under the hood, inserting data at (or removing from) the
beginning of a list can require shifting every other element in the list.
Queues have a very simple API. A
Queue
can have "infinite" (until the computer runs
out of memory) capacity, but it is more commonly bounded to some maximum size.
The primary methods are
put()
and
get()
, which add an element to the back of
the line, as it were, and retrieve them from the front, in order. Both of these methods
accept optional arguments to govern what happens if the operation cannot successfully
complete because the queue is either empty (can't get) or full (can't put). The default
behavior is to block or idly wait until the
Queue
object has data or room available
to complete the operation. You can have it raise exceptions instead by passing the
block=False
parameter. Or you can have it wait a defined amount of time before
raising an exception by passing a
timeout
parameter.
www.it-ebooks.info
Python Data Structures
Do'stlaringiz bilan baham: |