IT评测·应用市场-qidao123.com

标题: Python | 列队取奶茶 [打印本页]

作者: 农妇山泉一亩田    时间: 2024-6-15 00:27
标题: Python | 列队取奶茶
在 Python 语言中,尺度库中的queue模块提供了多种队列的实现,比如普通队列和优先级队列,因此你可以使用queue.Queue类来创建队列,不外我们依旧可以使用列表来模拟队列的实现。

  1. #导入queue模块
  2. import queue
  3. #创建一个对列
  4. q = queue.Queue()
  5. #通过put实现入队操作
  6. q.put(1)
  7. q.put(2)
  8. q.put(3)
  9. # 通过get()实现出队操作
  10. item = q.get() #出队并返回队列中的元素
  11. print(item)  #输出1
复制代码
也可以用列表模拟队列(上道题用列表实现了栈):
 
  1. ueue = []
  2. #入队操作
  3. queue.append("Tom")
  4. queue.append("Jerry")
  5. queue.append("Mike")
  6. #出队操作
  7. remove_person = queue.pop(0)  #弹出并返回队列中的第一个元素
  8. #判断队列是否为空:
  9. if not queueL
  10.     print("队列为空")
  11. else:
  12.     print(f"队头元素:{queue[0]}")
复制代码
由此可见,在列表中,假如直接pop(),那么将会弹出列表的最末尾一个值;而假如pop(0),那么将会弹出列表中的第一个元素

按照列表模拟队列的写法如下:
  1. n = int(input())
  2. persons = input().split()
  3. m = int(input())
  4. for _ in range(m):
  5.     ope = input().split()
  6.     opt = int(ope[0])
  7.     if opt == 1:
  8.         if persons:
  9.             move_person = persons.pop(0)
  10.     if opt == 2:
  11.         persons.append(ope[1])
  12. if persons:
  13.     print(persons.pop(0))
  14. else:
  15.     print("There are no more people in the queue.")
复制代码
按照queue模块的写法如下:


免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。




欢迎光临 IT评测·应用市场-qidao123.com (https://dis.qidao123.com/) Powered by Discuz! X3.4