MyTetra Share
Делитесь знаниями!
Using Lists as Queues / Использование списка как стека
Время создания: 04.09.2017 13:34
Текстовые метки: code
Раздел: Python - Types data - Списки
Запись: xintrea/mytetra_db_mcold/master/base/15045212720vw7vqwhtj/text.html на raw.githubusercontent.com

Using Lists as Queues

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 arrival
deque(['Michael', 'Terry', 'Graham'])
Так же в этом разделе:
 
MyTetra Share v.0.65
Яндекс индекс цитирования