【问题标题】:for loop in python skips [duplicate]python中的for循环跳过[重复]
【发布时间】:2015-05-17 21:58:21
【问题描述】:

我在 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]

我该如何解决这个问题?

【问题讨论】:

标签: python python-3.x


【解决方案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 指向某个特定位置的元素.

【讨论】:

    【解决方案2】:

    如果您在迭代列表时尝试改变列表,预计会看到这样的结果。

    换一种干净的方式怎么样:

    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]
    

    【讨论】:

      猜你喜欢
      • 2014-07-30
      • 2011-10-11
      • 1970-01-01
      • 2013-02-01
      • 2020-10-18
      • 1970-01-01
      • 2021-08-23
      • 2012-09-29
      相关资源
      最近更新 更多