我想要制作一个程序,其中列表添加和删除,并使用队列项目,但是,在我的代码中存在需要修复的问题。请帮帮我,谢谢。
class Queue:
def __init__(self):
self.items = ["Jene Dayao", "MJ Formaran", "Hans Matias", "Candy Santos", "Ian Domingo"]
def view(self):
print (self.items)
def enqueue(self, item):
item = input ("Name of the student: ")
self.items.insert(item)
def dequeue(self):
return self.items.pop()
print ("Student has finished photo taking!")
while True:
print ("School ID Picture Taking Queue")
print ("Select a function...")
print ("")
print ("1. See the student's active list")
print ("2. A student has finished picture taking")
print ("3. Add another student to the list")
option = int(input("Enter your choice: "))
if option == 1:
view ()
elif option == 2:
enqueue ()
elif option == 3:
dequeue ()
发布于 2020-10-02 04:14:46
下一次--尝试发布你遇到的错误,而不是写“我的代码中有问题需要修复”,这样人们就会知道如何帮助你。
此代码有多个问题:
Queue
类的函数,而不初始化它。应该是: # Must be initialized outside the loop, otherwise you will re-create
# it every time, discarding your changes
queue = Queue()
while True:
...
option = int(input("Enter your choice: "))
if option == 1:
queue.view()
elif option == 2:
queue.enqueue()
elif option == 3:
queue.dequeue()
enqueue
中,您要求用户输入他想要添加的学生的姓名。这是可以的,但问题是,您也期望从函数中接收来自外部的项目。从函数签名中移除item
,保持如下方式:def enqueue(self):
input
用于接收用户的数字。若要接收学生姓名应具有的类型的raw_input
,请使用string
item = raw_input("Name of the student: ")
self.items.insert(item)
不能工作,因为函数insert
应该接收要添加的项及其在列表中的索引。如果您不关心索引,只需使用:self.items.append(item)
q.enqueue
,将一个学生添加到列表中。当用户选择第二个选项时,要调用q.dequeue
,将学生从列表中删除:q = Queue()
if option == 1:
q.view()
elif option == 2:
q.dequeue()
elif option == 3:
q.enqueue()
最后一件事--在使用之前阅读您使用的函数的文档是一个很好的实践。有时候你可能会觉得你应该如何称呼他们的名字,但正如你所看到的,情况并不总是如此。
诚挚的问候。
发布于 2020-10-02 04:05:48
python中的最终队列实现
您的代码有几个问题:
- initialize an object of the class
- use only functions and drop using classes altogether.
我将讨论所有的问题
下面的方法使用类。
class Queue:
def __init__(self):
self.items = ["Jene Dayao", "MJ Formaran",
"Hans Matias", "Candy Santos", "Ian Domingo"]
def view(self):
print(self.items)
def enqueue(self, item):
self.items.append(item)
print("")
def dequeue(self):
print("Student has finished photo taking!")
return self.items.pop(0)
queue = Queue() # initializing an object of the class Queue
while True:
print("School ID Picture Taking Queue")
print("Select a function...")
print("")
print("1. See the student's active list")
print("2. Add another student to the list")
print("3. A student has finished picture taking")
option = int(input("Enter your choice: "))
if option == 1:
queue.view()
elif option == 2:
item = input("Name of the student: ") # taking the new students name
queue.enqueue(item)
elif option == 3:
queue.dequeue()
https://stackoverflow.com/questions/64171102
复制相似问题