循环不循环遍历列表中的所有元素

时间:2012-02-21 06:21:16

标签: python-3.x

我有

print(len(pcb.resources))
for res in pcb.resources:
    print ("Releasing resource: " + res.name)
    self.releaseResource(res.name, pcb)
print("After: " + str(len(pcb.resources)))

哪个输出

2 # from 1st print: this is correct, I have 2 elements in list
Releasing resource: R1 # is it not looping through the 2nd element? Notice the len() is 2
After: 1 # from print after loop. I am expecting 0

更新

我注意到它与函数调用有关。 releaseResource。但是releaseResource如何影响调用循环?

def releaseResource(self, name, pcb = None):
    callScheduler = pcb is not None # if pcb is set, means calling from release resource, so dont call scheduler 1st

    if pcb is None:
        pcb = self.running

    # check if resource exists
    if not any(rcb.name == name for rcb in self.resources): 
        return False    
    rcb = next(r for r in self.resources if r.name == name)

    # remove resource from running pcb's resources
    pcb.resources.remove(rcb)

    if len(rcb.waitingList) == 0:
        # no waiting processes: resource is free
        rcb.status = RCB.STATUS_FREE
        rcb.heldBy = None
    else:
        # make dequeue from resource waiting list
        pcb = rcb.waitingList.popleft()

        # put resource into process resources list
        pcb.resources.append(rcb)
        rcb.heldBy = pcb

        # make it ready
        pcb.status = PCB.STATUS_READY
        pcb.statusList = self.readyList
        self.readyList.enqueue(pcb)

        # call scheduler
        if callScheduler:
            self.scheduler()

    return True

1 个答案:

答案 0 :(得分:4)

在我看来,您修改了releaseResource中迭代的列表,即行pcb.resources.remove(rcb)。试试这个:

for res in pcb.resources[:]:
    print ("Releasing resource: " + res.name)
    self.releaseResource(res.name, pcb)

请参阅documentation