我有一个Python双端队列,每次都附加在该双端队列中。
pre_label = collections.deque(maxlen=5)
while True:
#do something
function(name)
pre_label.append()
我有:
pre_label = deque(['john', 'zari', 'fai'], maxlen=3)
我希望每10秒输出以下内容:
pre_label = deque([], maxlen=3)
答案 0 :(得分:0)
因此,有几种方法可以解决这个问题:
from collections import deque
deck = deque([], maxlen=3)
## Threaded solution
from threading import Thread
import time
def clear_deque():
""" This is a small function to clear the queue and print the contents when cleared"""
global deck # You should probably avoid globals, but we need a reference to the underlying object to make the clear actually work.
while(True):
time.sleep(3) # you'd want to increase this to 10. Also, sleeping at the start to allow some time before the clear to happen the first time.
contents = list(deck)
deck = deque([], maxlen=3)
print("\n |> Deck = {}".format(contents))
t = Thread(target=clear_deque) # Making a new thread to call this one function
t.daemon=True # Marking the thread as a daemon, so that it can be killed when the program exits normally
t.start() # annnd starting the thread!
# And a dumb loop to verify the functionality
while True:
v = input("Add stuff> ")
deck.append(v)
t.join()
import asyncio
import random
from collections import deque
deck = deque([], maxlen=10)
async def clear_deque():
global deck
while True:
await asyncio.sleep(3)
contents = list(deck)
print(f"\n |> Deck contents: {contents}")
deck = deque([], maxlen=10)
async def add_to_deque():
while True:
await asyncio.sleep(random.random())
v = random.randint(1, 10)
print(f"Adding: {v}")
deck.append(v)
loop = asyncio.get_event_loop()
actions = asyncio.gather(add_to_deque(), clear_deque())
loop.run_until_complete( actions )