Skip to main content
 首页 » 编程设计

python之从python中的队列中提取

2024年09月07日11webabcd

我在尝试从队列中提取元素直到给定数字时遇到问题。如果给定的号码没有排队,代码应该让队列为空并给出一条消息说明这一点。

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

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)