for python跳过循环

时间:2015-03-15 20:24:30

标签: python python-3.x

我在python 3.4中有一个for循环

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

让我们举例说明

customer_waiting[4]
    if customer.Source == Self.location

然后循环删除

customer_waiting[4]customer_waiting[5]

然后转到位置4.然后循环继续并查看 customer_waiting[5]但它实际上是在customer_waiting[6]跳过customer_waiting[5]

我该如何解决这个问题?

2 个答案:

答案 0 :(得分:1)

您需要复制或使用反转:

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)

使用反转:

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)

永远不要改变你正在迭代的列表,而不是复制或使用反转,否则你将最终跳过你已经看过的元素,如果你删除了一个元素你改变了哪个元素python在你开始迭代时指向某个位置

答案 1 :(得分:0)

如果你试图在迭代它时改变列表,期望看到这样的结果。

如何改变干净的方式:

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]