for loop in python skips
本问题已经有最佳答案,请猛点这里访问。
我在python 3.4中有一个for循环,如下所示
1 2 3 4 5 | def checkCustometers(self): for customer in self.customers_waiting: if customer.Source == self.location: #if the customer wants to get on at this floor, self.customers_inside_elevators.append(customer) #place customer into elevator self.customers_waiting.remove(customer) #The customer isent waiting anymore |
比如说在
1 2 | customer_waiting[4] if customer.Source == Self.location |
然后循环删除
转到位置4。然后循环继续并查看
我怎么修这个?
您需要复制或反向使用:
1 2 3 4 5 | def checkCustometers(self): for customer in self.customers_waiting[:]: if customer.Source == self.location: #if the customer wants to get on at this floor, self.customers_inside_elevators.append(customer) #place customer into elevator self.customers_waiting.remove(customer) |
使用反向:
1 2 3 4 5 | def checkCustometers(self): for customer in reversed(self.customers_waiting): if customer.Source == self.location: #if the customer wants to get on at this floor, self.customers_inside_elevators.append(customer) #place customer into elevator self.customers_waiting.remove(customer) |
号
不要在不复制或使用reversed的情况下改变正在迭代的列表,否则最终会跳过元素,正如您已经看到的那样,如果删除一个元素,则会在开始迭代时更改python指向某个特定位置的元素。
如果您试图在遍历列表时改变列表,那么应该看到这样的结果。
换个干净的方法怎么样:
1 2 3 | def checkCustometers(self): self.customers_inside_elevators += [c for c in self.customers_waiting if c.Source == self.location] self.customers_waiting = [c for c in self.customers_waiting if c.Source != self.location] |