how to implement a queue-like container with sort function
Steven D'Aprano
steve+comp.lang.python at pearwood.info
Thu Nov 28 22:32:40 EST 2013
On Fri, 29 Nov 2013 13:03:00 +1100, Chris Angelico wrote:
> On Fri, Nov 29, 2013 at 12:54 PM, iMath <redstone-cold at 163.com> wrote:
>> the container is similar to queue ,but queue doesn't have a sort
>> function
>
> It's either a queue that can be sorted, or a list with a length limit.
> You could fairly easily implement either, because in Python, anything
> can be subclassed. But I think possibly the easiest way is to simply
> turn your queue into a list when you want to work with it:
>
>>>> import queue
>>>> a=queue.Queue(10)
>>>> a.put("asdf")
>>>> a.put("qwer")
>>>> a.put("zxcv")
>>>> a.put("1234")
>>>> sorted(a.queue)
> ['1234', 'asdf', 'qwer', 'zxcv']
>
> Though I don't know if this is what you meant. Putting too much onto a
> queue.Queue will block. Were you wanting it, instead, to discard
> entries? If so, which?
Unless the OP needs all the extra threading-related powers of the queue
module, I'd just stick to a simple, single-threaded queue object. These
easiest way to do that is with a deque, which is a double-ended queue.
The threading Queue class is based on a deque, so this will be at least
as fast:
py> from collections import deque
py> my_queue = deque([], 5) # maximum of five items
py> my_queue.append(7)
py> my_queue.append(3)
py> my_queue.append(9)
py> sorted(my_queue)
[3, 7, 9]
py> my_queue.append(2)
py> my_queue.append(0)
py> my_queue.append(4)
py> my_queue
deque([3, 9, 2, 0, 4], maxlen=5)
py> sorted(my_queue)
[0, 2, 3, 4, 9]
--
Steven
More information about the Python-list
mailing list