python - 从python队列中提取

标签 python queue

我在尝试从队列中提取元素直到达到给定数量时遇到问题。如果给定的号码没有排队,代码应该将队列留空并给出一条消息。

相反,我收到此错误消息,但无法解决它:

Traceback (most recent call last):
  File "python", line 45, in <module>
IndexError: list index out of range

这是我当前的代码:

class Queue():
  def __init__(self):
      self.items = []
  def empty(self):
    if self.items == []:
      return True
    else:
      return False
  def insert(self, value):
        self.items.append(value)
  def extract(self):
    try:
      return self.items.pop(0)
    except:
      raise ValueError("Empty queue")
  def last(self):
    if self.empty():
      return None
    else:
      return self.items[0]

import random
def randomlist(n2,a2,b2):
    list = [0]  * n2
    for i in range(n2):
      list[i] = random.randint(a2,b2)
    return list

queue1=Queue()
for i in range (0,10):
  queue1.insert(randomlist(10,1,70)[i])
if queue1.empty()==False :
  print("These are the numbers of your queue:\n",queue1.items)

test1=True
while test1==True:
  s=(input("Input a number:\n"))
  if s.isdigit()==True :
   test1=False
   s2=int(s)
  else:
    print("Wrong, try again\n")

for i in range (0,10) :    
  if queue1.items[i]!=s2 :
    queue1.extract()
  elif queue1.items[i]==s2 :
    queue1.extract()
    print ("Remaining numbers:\n",queue1.items)
    break
if queue1.empty()==True :
  print ("Queue is empty now", cola1.items)

最佳答案

extract elements from a queue until a given number. If the given number is not queued, the code should leave the queue empty and give a message saying that.

while not queue.empty():
    if queue.extract() == target:
        print('Found! Remaining numbers:', queue.items)
        break
else:
    print('Not found! Remaining numbers:', queue.items)

关于python - 从python队列中提取,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48477200/

相关文章:

python - 如何在超时的情况下动态导入不安全的 Python 模块?

python - 使用 wkhtmltopdf 在 PDF 中重用相同的 SVG

python - 异步队列收集协程的返回值

c - 如何使用linux内核列表实现队列?

java - 如何使用 Java/JMS 从队列中丢弃消息?

objective-c - 如何在 Objective-C 中创建和使用队列?

python - 如何导入文件名包含 '-'字符的python模块

python - 如何使用 flask-bootstrap 将标题文本垂直和水平居中

python - 将 dict 转换为 Python 中的另一个结构

c - 使用链表实现队列中的"Segmentation fault (core dumped)"