<p>我在做一个假设很简单的python挑战,一个朋友给了我一个电梯和它运动背后的逻辑。一切都进行得很顺利,直到我不得不写下如何确定电梯是否可以移动,并在到达下一个排队楼层的途中撞上一个叫的楼层。你知道吗</p>
<pre class="lang-py prettyprint-override"><code>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()
</code></pre>
<p>所以在For循环中,有一个嵌套的If/Else循环,我假设它将与For循环中的其余代码一起迭代。但是,当我运行代码时,在到达If/Else循环时,它会跳出For循环,继续它的快乐之路,而忽略了需要在数组中进行的任何进一步迭代。这是怎么回事?你知道吗</p>
<p>当我用一个基本的楼层测试集运行代码时,下面是我得到的输出。你知道吗</p>
<pre><code>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
</code></pre>
<p>它之所以跳过第6层,是因为从正在迭代的列表中删除了数据。你知道吗</p>
<pre><code>l=[3,6,9,10,14]
for i in l:
print(i)
</code></pre>
<p>输出:
三
6
9
10
14个</p>
<pre><code>for i in l:
print(i)
l.remove(i)
</code></pre>
<p>输出:
三
9
14个</p>