首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > perl python >

Python示意队列

2012-08-28 
Python表示队列It is also possible to use a list as a queue, where the first element added is the fi

Python表示队列
It is also possible to use a list as a queue, where the first element added is the first element retrieved (“first-in, first-out”); however, lists are not efficient for this purpose. While appends and pops from the end of list are fast, doing inserts or pops from the beginning of a list is slow (because all of the other elements have to be shifted by one).

To implement a queue, use collections.deque which was designed to have fast appends and pops from both ends. For example:

>>> from collections import deque>>> queue = deque(["Eric", "John", "Michael"])>>> queue.append("Terry")           # Terry arrives>>> queue.append("Graham")          # Graham arrives>>> queue.popleft()                 # The first to arrive now leaves'Eric'>>> queue.popleft()                 # The second to arrive now leaves'John'>>> queue                           # Remaining queue in order of arrivaldeque(['Michael', 'Terry', 'Graham'])

热点排行