简体   繁体   English

为什么我的If / Else循环会脱离我的For循环?

[英]Why does my If/Else loop break out of my For loop?

I'm doing a supposedly simple python challenge a friend gave me involving an elevator and the logic behind its movements. 我正在做一个据说很简单的python挑战,一个朋友给我讲了一部电梯及其运动背后的逻辑。 Everything was going well and good until I got to the point where I had to write how to determine if the elevator could move hit a called floor en route to its next queued floor. 一切都进展顺利,直到我不得不写出如何确定电梯是否可以在到达下一个排队楼层的途中撞到被叫楼层的点上为止。

def floorCompare(currentFloor,destinationFloor,calledFloor):
    if calledFloor > currentFloor and calledFloor < destinationFloor:
        return(True)
    elif calledFloor < currentFloor and calledFloor > destinationFloor:
        return(True)
    else:
        return(False)

floor = "1"
doors = "closed"
queue = []
def elevator(): # function defines how the elevator should move
    print("The Elevator is on floor: 1. The doors are "+doors+".")
    for x in range(int(input("How many floors need to be visited? "))):
        callFloor = int(input("Floor to call the elevator to: "))
        queue.append(callFloor)
        if callFloor > 10 or callFloor < 1:
            raise Exception(str(callFloor)+" is not a valid floor.")
    if queue[0] == 1:
        del queue[0]
        print("The elevator has arrived on floor 1, and the doors are open.")
    print("The queue of floors to visit is...",queue)
    for x in queue:
        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)
        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)
        if floorCompare(int(floor), int(queue[0]), int(addFloor)) == True:
            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")

elevator()

So in the For loop, there is a nested If/Else loop, which I would assume would be iterated along with the rest of the code in the for loop. 因此,在For循环中,有一个嵌套的If / Else循环,我认为它将与for循环中的其余代码一起进行迭代。 However, when I run the code, upon reaching the If/Else loop, it breaks out of the For loop and continues on its merry way, disregarding any further iterations that need to be done in the array. 但是,当我运行代码时,到达If / Else循环时,它脱离了For循环并以其快乐的方式继续进行,而忽略了数组中需要执行的任何其他迭代。 What's going on here? 这里发生了什么?

When I run the code with a basic trial set of floors, here's what I get as output. 当我使用一组基本的试用版代码运行代码时,这就是我得到的输出。

The Elevator is on floor: 1. The doors are closed.
How many floors need to be visited? 4
Floor to call the elevator to: 3
Floor to call the elevator to: 6
Floor to call the elevator to: 9
Floor to call the elevator to: 10
The queue of floors to visit is... [3, 6, 9, 10]
The elevator's doors are closed and it's moving to floor: 3
...

The elevator has arrived on floor 3, and the doors are open.
Floor to call the elevator to: 7
[6, 9, 10]
The elevator must hit this stop seperately.
The elevator's doors are closed and it's moving to floor: 9
...

The elevator has arrived on floor 9, and the doors are open.
Floor to call the elevator to: 3
[6, 10]
The elevator must hit this stop separately.

Process finished with exit code 0

The reason for the early exit is because you are modifying the list while looping on it. 提早退出的原因是因为您正在循环浏览列表时对其进行了修改。 To have a simple example: 举一个简单的例子:

l = [3,6,9,10]

for x in l:
    print(x)
    l.remove(x)

The output is 输出是

3
9

However, there are many other problems with your current code. 但是,当前代码还有很多其他问题。 Some I could catch are: 我可以捕捉到的一些是:

  1. You aren't adding the newly called floors inside the for loop. 您没有在for循环中添加新调用的楼层。
  2. The floorCompare method is being called with queue[0] as the destination, while that isn't the final one. 将使用queue[0]作为目标位置调用floorCompare方法,但这并不是最后一个方法。 As you can see, 7 was not considered en route since you compared 3 and 6 . 如您所见,因为您比较了36所以在途中未考虑7 You should have compared 3 and 10 , the farthest one. 您应该比较了最远的310

Also note that queue is not initially sorted, and the intermediate calls will also not be in order. 另请注意, queue最初并未排序,并且中间调用也将不按顺序进行。 So you need to keep that in mind while using it. 因此,在使用它时,请记住这一点。

I think your problem lies in the use of a for loop in conjunction with the queue.remove() function. 我认为您的问题在于将for循环与queue.remove()函数结合使用。 It seems like the for x in queue: operator runs into problems when you edit the list while it runs. 似乎for x in queue:在您运行列表时编辑该列表时,运算符会遇到问题。 I would recommend using while queue: instead and setting x to the first element. 我建议使用while queue:而是将x设置为第一个元素。

    while queue:
        x = queue[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.")
        queue.remove(x)
        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)
        if floorCompare(int(floor), int(queue[0]), int(addFloor)) == True:
            print("The elevator can hit this stop en route to its next one.")
        else:
            print("The elevator must hit this stop separately.")

The reason for it to skip floor 6, is because of removing the data from the list, which is being iterated. 之所以跳过第6层,是因为要从列表中删除正在迭代的数据。

l=[3,6,9,10,14]
for i in l:
    print(i)

Output: 3 6 9 10 14 输出:3 6 9 10 14

for i in l:
    print(i)
    l.remove(i)

output: 3 9 14 输出:3 9 14

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM