• python栈、队列的使用


    栈 

    #栈
    stack = [3, 4, 5]
    stack.append(6)
    stack.append(7)
    #stack
    [3, 4, 5, 6, 7]
    
    stack.pop()
    #7
    stack
    #[3, 4, 5, 6]
    stack.pop()
    #6
    

    queue

    Python的Queue模块提供一种适用于多线程编程的先进先出(FIFO)容器
    使用:put(),将元素添加到序列尾端,get(),从队列尾部移除元素。
    

     Queue.Queue(maxsize=0)   FIFO, 如果maxsize小于1就表示队列长度无限
           Queue.LifoQueue(maxsize=0)   LIFO, 如果maxsize小于1就表示队列长度无限
           Queue.qsize()   返回队列的大小 
           Queue.empty()   如果队列为空,返回True,反之False 
           Queue.full()   如果队列满了,返回True,反之False
           Queue.get([block[, timeout]])   读队列,timeout等待时间 
           Queue.put(item, [block[, timeout]])   写队列,timeout等待时间 
           Queue.queue.clear()   清空队列

    from queue import Queue
    
    q = Queue()
    
    for i in range(3):
        q.put(i)
    
    while not q.empty():
        print(q.get())
    
    #
    0
    1
    2

    LifoQueue

    使用后进先出序

    from queue import LifoQueue
    
    q = LifoQueue()
    
    for i in range(3):
        q.put(i)
    
    while not q.empty():
        print(q.get())
    #
    2
    1
    0

    PriorityQueue

    依据队列中内容的排序顺序(sort order)来决定那个元素将被检索

    from queue import PriorityQueue
    
    
    class Job(object):
        def __init__(self, priority, description):
            self.priority = priority
            self.description = description
            print('New job:', description)
            return
    
        def __lt__(self, other):
            #定义小于操作符(<)的行为
            return self.priority < other.priority
    
    q = PriorityQueue()
    
    #q.put((数字,值)),特点:数字越小,优先级越高
    q.put(Job(5, 'Mid-level job'))
    q.put(Job(10, 'Low-level job'))
    q.put(Job(1, 'Important job'))
    
    while not q.empty():
        next_job = q.get()
        print('Processing job', next_job.description)
    
    #
    New job: Mid-level job
    New job: Low-level job
    New job: Important job
    Processing job: Important job
    Processing job: Mid-level job
    Processing job: Low-level job
    

     collections.deque模块

    是python标准库collections中的一项,它提供了两端都可以操作的序列,这意味着,在序列的前后你都可以执行添加或删除操作。

    append('a')右边入队列,appendleft('a')左边。

    pop()右边删除,popleft()左边删除。

    from collections import deque
    
    queue = deque(["Eric", "John", "Michael"])
    queue.appendleft('a')
    queue.append('b')
    print(queue)
    #deque(['a', 'Eric', 'John', 'Michael', 'b'])
    
    
    queue.popleft()                 # The first to arrive now leaves
    queue.pop()
    print(queue)
    #deque(['Eric', 'John', 'Michael'])
  • 相关阅读:
    ORA00911: 无效字符
    在创建外键约束时追加on delete cascade或on delete set null
    仿58同城下拉菜单
    经典SQL语句大全
    Substitution 使用方法 页面缓存时的局部刷新
    解决IE8开发人员工具无法使用的问题
    ASP.NET 页面缓存 @ OutputCache
    关于clientWidth、offsetWidth、clientHeight、offsetHeight的测试比较
    调用ThunderAgent 迅雷局域网版的开发
    仿58同城 tips 鼠标悬停提示 类似title、alt
  • 原文地址:https://www.cnblogs.com/onenoteone/p/12441781.html
Copyright © 2020-2023  润新知