“Lista Python jako kolejka” Kod odpowiedzi

Python Zdobądź przedmiot z kolejki

"""put and get items from queue"""
>>> from Queue import Queue
>>> q = Queue()
>>> q.put(1)
>>> q.put(2)
>>> q.put(3)
>>> print list(q.queue)
[1, 2, 3]

>>> q.get()
1
>>> print list(q.queue)
[2, 3]
Defeated Dolphin

Kolejka Python

from queue import Queue  # watch out with the capital letters

# Making the queue
queuename = Queue()

# We use .put() to insert value and .get() to pop the first one.
# You can think this as a normal queue

queuename.put(1)  # adds int 1 to index 0
# To access the queue, you need to change it to list
print(list(queuename.queue))
# Output : [1]

queuename.put(2)  # adds int 2 to index 1
print(list(queuename.queue))
# Output: [1,2]

queuename.get()  # removes index 0 (int 1)
print(list(queuename.queue))
# Output: [2]

# We can simulate the same effects using normal list, but the longer the queue
# the more ineffecient it becomes

queuesimulate.append(1)
print(queuesimulate)
# Output : [1]

queuesimulate.append(2)
print(queuesimulate)
# Output: [1,2]

queuesimulate.pop(0)  # 0 is the index number
print(queuesimulate)
# Output: [2]
Sparkling Seahorse

Lista Python jako kolejka

>>> 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'])
khuDDD

Odpowiedzi podobne do “Lista Python jako kolejka”

Pytania podobne do “Lista Python jako kolejka”

Więcej pokrewnych odpowiedzi na “Lista Python jako kolejka” w Python

Przeglądaj popularne odpowiedzi na kod według języka

Przeglądaj inne języki kodu