没有所谓的捷径
一切都是时间最平凡的累积

python实现不重复队列queque

默认情况下,queue.Queue队列是没有判断重复性的,也不支持in判断

以下是queue.put源码

def put(self, item, block=True, timeout=None):
    '''Put an item into the queue.

    If optional args 'block' is true and 'timeout' is None (the default),
    block if necessary until a free slot is available. If 'timeout' is
    a non-negative number, it blocks at most 'timeout' seconds and raises
    the Full exception if no free slot was available within that time.
    Otherwise ('block' is false), put an item on the queue if a free slot
    is immediately available, else raise the Full exception ('timeout'
    is ignored in that case).
    '''
    with self.not_full:
        if self.maxsize > 0:
            if not block:
                if self._qsize() >= self.maxsize:
                    raise Full
            elif timeout is None:
                while self._qsize() >= self.maxsize:
                    self.not_full.wait()
            elif timeout < 0:
                raise ValueError("'timeout' must be a non-negative number")
            else:
                endtime = time() + timeout
                while self._qsize() >= self.maxsize:
                    remaining = endtime - time()
                    if remaining <= 0.0:
                        raise Full
                    self.not_full.wait(remaining)
        self._put(item)
        self.unfinished_tasks += 1
        self.not_empty.notify()

要实现不重复队列,在put加入队列前需要判断加入的元素是否存在,可以重写queue.Queue类的put方法

如下,定义一个类,继承queue.Queue,在加入队列前进行判断,如果存在,直接返回

class Superqueue(queue.Queue):
    """不重复队列
    @param put(): 重写Queue.put方法,实现队列元素不重复
    """

    def __init__(self):
        super(Superqueue, self).__init__()

    def put(self, item, block=True, timeout=None, unique=True):
        """增加了unique参数"""
        with self.not_full:
            # 新增代码开始
            if unique:
                if item in self.queue:
                    return
            # 新增代码结束
            if self.maxsize > 0:
                if not block:
                    if self._qsize() >= self.maxsize:
                        raise Full
                elif timeout is None:
                    while self._qsize() >= self.maxsize:
                        self.not_full.wait()
                elif timeout < 0:
                    raise ValueError("'timeout' must be a non-negative number")
                else:
                    endtime = time() + timeout
                    while self._qsize() >= self.maxsize:
                        remaining = endtime - time()
                        if remaining <= 0.0:
                            raise Full
                        self.not_full.wait(remaining)
            self._put(item)
            self.unfinished_tasks += 1
            self.not_empty.notify()

 

赞(0) 打赏
声明:本站发布的内容(图片、视频和文字)以原创、转载和分享网络内容为主,若涉及侵权请及时告知,将会在第一时间删除,联系邮箱:lwarm@qq.com。文章观点不代表本站立场。本站原创内容未经允许不得转载,或转载时需注明出处:红岩子 » python实现不重复队列queque
分享到: 更多 (0)

评论 抢沙发

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址

今天所做的努力都是在为明天积蓄力量

联系我们赞助我们