从队列中弹出项目不会删除所有项目

时间:2020-04-18 18:36:29

标签: python python-3.x

目前,我正在学习有关堆栈和队列的信息。尝试实施新知识,但无法理解为什么弹出无法将所有元素从我的队列中删除,只是其中的一半。在这段代码中,我尝试为队列做一个例子,但是我知道,使用这种弹出方法,我创建了LIFO方式,即堆栈。因此,请不要考虑这一点,我只是想找到一个答案,“为什么我的for循环仅删除列表中一半的元素”。

这是我的代码,其中我排空队列或刚开始与客户排队。然后使用for循环,我在队列中添加1到10之间的数字。然后使用for循环,我尝试从该行中删除所有客户,并在删除该客户iD时将其打印出来。例如,删除客户iD 10、9、8等。

但是,它只删除该行中一半的客户,当我在for循环之后打印队列时,我仍然有5个元素。

queue = [] # or a line of customers before they have arrived.
print("Empty line: ", queue)
for number in range(1, 11):
    queue.append(number) # here i add 10 customers to the line.
print("Line after 10 people have arrived: ", queue)
for number in queue:
    print("Removed customer iD: ", queue.pop()) # here i tried to remove all customers
print(queue)

输出:

Empty line:  []
Line after 10 people have arrived:  [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Removed customer iD: 10
Removed customer iD: 9
Removed customer iD: 8
Removed customer iD: 7
Removed customer iD: 6
[1, 2, 3, 4, 5]

1 个答案:

答案 0 :(得分:0)

作为标准做法,您永远不需要修改要循环的迭代器。相反,请使用单独的迭代器进行循环,然后在循环体中修改您的队列数组:

queue = [] # or a line of customers before they have arrived.                         
print("Empty line: ", queue)                                                          
for number in range(1, 11):                                                           
    queue.append(number) # here i add 10 customers to the line.                       
print("Line after 10 people have arrived: ", queue)                                   
for i in range(0, len(queue)):                                                        
    print("Removed customer iD: ", queue.pop()) # here i tried to remove all customers

我正在遍历范围迭代器并修改for循环主体中的队列。

看到原始队列中剩余元素的一半的原因是因为迭代器在每次通过时都根据数组的长度检查当前索引,数组的索引和长度都达到{{1} }会停止for循环:

5

打印以下内容:

for index, num in enumerate(queue):
    queue.pop()
    print("index num", { "index":index, "num":num , "len": len(queue)})
相关问题