队列类,出队和入队?Python
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20557440/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Queue Class, dequeue and enqueue ? python
提问by user2928929
So I have this question and it says create a class queue and make the method dequeue and enqueue
所以我有这个问题,它说创建一个类队列并使方法出队和入队
Here's what I have so far, could someone direct me on the right track?
这是我到目前为止所拥有的,有人可以指导我走上正确的道路吗?
class queue:
def __init__(self,queue):
self.queue = []
def dequeue(self):
if len(queue) > 0:
e = queue[0]
queue = list[1:len(queue)]
else:
return "There are no elements to remove"
def enqueue(self,element):
queue.insert([-1], element)
采纳答案by abarnert
There are a few problems here.
这里有几个问题。
queueby itself refers to your class, not to the instance's attribute with the same name, which isself.queue. You have to use theself.all the time. And it would really help to give the class and its attribute different names, to avoid this confusion. (It would also help to use PEP 8 style and name the classQueue.)- When the queue is not empty, you do compute the return value
e, but you neverreturnit; you just fall off the end of the function, which means you automatically returnNone. list[1:len(queue)]is trying to slice the typelist, not your actual list (self.queue). What you wanted isself.queue[1:len(queue)].- You probably don't want to return a string—which could be a perfectly valid thing to stick in the queue—on errors. That's exactly what exceptions are for.
- Your
__init__takes an argument that it never uses. You probably wanted to use this as a starting value for the queue's contents. And you probably also want to make it optional. - The
list.insertfunction doesn't take alistlike[-1]for its first argument, it takes an index like-1. - If this is Python 2.x, you do not want to create classic classes; if you have nothing else to inherit from, inherit from `object.
- It looks like you may be mixing tabs and spaces for indentation. Don't do that.
queue本身是指您的class,而不是具有相同名称的实例属性,即self.queue. 你必须一直使用self.。为类及其属性提供不同的名称,以避免这种混淆,这真的很有帮助。(使用 PEP 8 样式并命名类也有帮助Queue。)- 当队列不为空时,你会计算返回值
e,但你永远不会计算return;你只是从函数的末尾掉下来,这意味着你会自动返回None. list[1:len(queue)]正在尝试切片类型list,而不是您的实际列表 (self.queue)。你想要的是self.queue[1:len(queue)].- 您可能不想在出现错误时返回一个字符串——这可能是一个非常有效的东西,可以放在队列中。这正是例外的用途。
- 你
__init__接受一个它从不使用的参数。您可能希望将其用作队列内容的起始值。而且您可能还想让它成为可选的。 - 该
list.insert函数的第一个参数不采用listlike[-1],它采用像-1. - 如果这是 Python 2.x,您不想创建经典类;如果您没有其他可继承的东西,请从`object 继承。
- 看起来您可能会混合使用制表符和空格进行缩进。不要那样做。
Plus, there are a few things that could be simpler:
另外,还有一些事情可以更简单:
- If you want to slice to the end of a list, just leave off the end, like
self.queue[1:], instead of usinglen(self.queue). - But to both fetch and remove a value from the left side of a list even more simply, you can use
pop(0). - To add a value to the right side of a list, you can use
append. - To check if a list is non-empty, just do
if the_list, notif len(the_list) > 0. Empty collections are always falsey, and non-empty collections truth. - But you really don't need to check anyway—if the list is empty,
popwill raise an exception, which is exactly what you wanted to do.
- 如果您想切片到列表的末尾,只需离开末尾,例如
self.queue[1:], 而不是使用len(self.queue)。 - 但是要更简单地从列表左侧获取和删除值,您可以使用
pop(0). - 要将值添加到列表的右侧,您可以使用
append. - 要检查列表是否为非空,只需执行
if the_list,而不是if len(the_list) > 0。空集合总是假的,非空集合总是假的。 - 但无论如何你真的不需要检查——如果列表为空,
pop将引发异常,这正是你想要做的。
So:
所以:
class Queue(object):
def __init__(self, queue=None):
if queue is None:
self.queue = []
else:
self.queue = list(queue)
def dequeue(self):
return self.queue.pop(0)
def enqueue(self, element):
self.queue.append(element)
If you want to customize the exception, so it says, e.g., IndexError: dequeue from empty Queueinstead of IndexError: pop from empty list, you can do that with a trystatement:
如果你想自定义异常,所以它说,例如,IndexError: dequeue from empty Queue而不是IndexError: pop from empty list,你可以用一个try语句来做到这一点:
def dequeue(self):
try:
return self.queue.pop(0)
except IndexError:
raise IndexError('dequeue from empty Queue')
If you want to test that your queue class works properly, you will need to write test functions, and then call them. For example:
如果要测试队列类是否正常工作,则需要编写测试函数,然后调用它们。例如:
def test_queue():
q = Queue()
for i in range(10):
q.enqueue(i)
for i in range(10):
value = q.dequeue()
if value != i:
print('Value #{} should be {} but is {}'.format(i, i, value))
try:
value = q.dequeue()
except IndexError:
pass # we _want_ an error here
else:
print('#10 should raise an IndexError, but got {}'.format(value))
if __name__ == '__main__':
test_queue()
Now you can just run the file as a script, and it will run your tests.
现在您可以将文件作为脚本运行,它会运行您的测试。
In real life, you'll want to think of more complete tests that cover all the weird edge cases you can think of. And you'll probably want to use the unittestlibrary or a third-party solution like noseto organize and simplify your tests.
在现实生活中,您会想要考虑更完整的测试,以涵盖您能想到的所有奇怪的边缘情况。您可能希望使用unittest库或第三方解决方案nose来组织和简化您的测试。
回答by PasteBT
Use self.queue, otherwise you will get error
使用self.queue,否则会报错
you did not return element when self.queue is not empty
当 self.queue 不为空时,你没有返回元素
And you'd better not return a message when queue is empty, should just raise exception
当队列为空时你最好不要返回消息,应该只引发异常
class Queue:
def __init__(self,queue):
self.queue = []
def dequeue(self):
return self.queue.pop(0)
def enqueue(self,element):
self.queue.append(element)

