python中从队列里取出全部元素的两种写法
直接上代码:
import queue
import timeq = queue.Queue()q.put(10)
q.put(20)
q.put(30)
q.put('a')
q.put('b')
q.put('c')# 取出q中的元素(第一种写法)
while True:if not q.empty():item = q.get()print(f"从队列中获取了: {item}")time.sleep(1) # 模拟处理时间else:# 如果队列为空,则退出循环break# 取出q中的元素(第二种写法)
while not q.empty():item = q.get()print(f"从队列中获取了: {item}")time.sleep(1) # 模拟处理时间
结果(分别运行写法一和写法二,都是如下结果):
注意事项就只有一条,那就是如果想要取出队列中的全部元素,不要忘了使用while循环!