You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

为何我的If/Else逻辑会导致Python For循环提前终止?

为什么你的电梯模拟循环会提前跳出?

嘿,我一眼就看出问题所在了——你在遍历列表的同时修改了原列表,这是Python里非常常见的坑,直接导致了循环跳过元素、提前结束。

问题根源

你用for x in queue来遍历待访问的楼层队列,但在循环体内调用了queue.remove(x)来删除当前处理的楼层。Python的for循环是基于列表的迭代器工作的,当你修改原列表(比如删除元素),迭代器的索引会彻底混乱:

  • 初始队列是[3,6,9,10],第一次迭代x取到3,执行queue.remove(3)后队列变成[6,9,10]
  • 迭代器接下来会去访问原列表的第二个位置(对应现在的9),直接跳过了6,所以你看到电梯直接从3跳到了9,完全忽略了6这个目标楼层

解决方案

有两种简单的修复方式,推荐第二种更直观:

方式1:遍历队列的副本

把循环改成遍历原队列的副本,这样即使修改原队列,也不会影响迭代过程:

for x in queue.copy():  # 遍历副本而非原列表
    print("The elevator's doors are closed and it's moving to floor:",x)
    floor = str(x)
    print("...")
    print()
    print("The elevator has arrived on floor "+floor+", and the doors are open.")
    queue.remove(x)
    # 后续代码不变...

方式2:用while循环替代for循环

这种方式更清晰,直接基于队列是否为空来控制循环,每次取出队列的第一个元素处理:

# 替换原来的for x in queue循环
while queue:
    x = queue.pop(0)  # 取出队列第一个元素并删除
    print("The elevator's doors are closed and it's moving to floor:",x)
    floor = str(x)
    print("...")
    print()
    print("The elevator has arrived on floor "+floor+", and the doors are open.")
    addFloor = int(input("Floor to call the elevator to: "))
    if addFloor > 10 or addFloor < 1:
        raise Exception(str(addFloor)+" is not a valid floor.")
    print(queue)
    # 避免队列为空时访问queue[0]抛出索引错误
    next_dest = int(queue[0]) if queue else 0
    if floorCompare(int(floor), next_dest, int(addFloor)):
        print("The elevator can hit this stop en route to its next one.")
    else:
        print("The elevator must hit this stop separately.")
    print("Continuing Queue")

额外小建议

你的floorCompare函数目前没有处理calledFloor等于currentFloor或destinationFloor的情况,比如如果用户在电梯到达3层时呼叫3层,函数会返回False,这显然不合理,可以修改一下:

def floorCompare(currentFloor, destinationFloor, calledFloor):
    # 处理同楼层的情况
    if calledFloor == currentFloor or calledFloor == destinationFloor:
        return True
    # 处理途中的情况
    if (calledFloor > currentFloor and calledFloor < destinationFloor) or \
       (calledFloor < currentFloor and calledFloor > destinationFloor):
        return True
    else:
        return False

内容的提问来源于stack exchange,提问作者UnbeknownstPraetorian

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.13 07:52:45