Python-神秘无限循环
我想弄明白为什么当x值为3时,这个循环是无限的Python-神秘无限循环,python,indexing,while-loop,infinite-loop,Python,Indexing,While Loop,Infinite Loop,我想弄明白为什么当x值为3时,这个循环是无限的 def mystery(x): a = [0, 4, 0, 3, 2] while x > 0: x = a[x] return "Done" 神秘(3)无限延伸 是因为当列表值已经是3时,它一直试图将x设置为3吗?是的,x始终是3。最初x是3,在索引3处list的值,即a[x]也是3。因此无限循环。记住数组索引从0开始,所以如果 a = [0, 4, 0, 3, 2] 然后a[3]==3 所以这条线 x = a[x]
def mystery(x):
a = [0, 4, 0, 3, 2]
while x > 0:
x = a[x]
return "Done"
神秘(3)无限延伸
是因为当列表值已经是3时,它一直试图将x设置为3吗?是的,x始终是3。最初x是3,在索引3处list的值,即a[x]也是3。因此无限循环。记住数组索引从0开始,所以如果
a = [0, 4, 0, 3, 2]
然后a[3]==3
所以这条线
x = a[x]
切勿将x
设置为3以外的任何值 “是否因为列表值已经为3时,它一直试图将x设置为3?”
对
a[3]
指向该列表中的3
。因此,x
只是被反复分配给3
。记住列表索引从零开始,所以a[3]=3。然后,尝试手动展开循环:
以此类推。可能代替
while x>0:
你想要while x!=a[x]:
。这将处理映射到自身的两个值,而不仅仅是其中一个。但如果存在任何循环(例如,a=[1,0,2,3,4]
将永远在0
或1
上循环),这仍然没有帮助。
def mystery(x): # Here x = 3
a = [0, 4, 0, 3, 2]
while x > 0: # Since x = 3 the program enters the loop
x = a[x] # a[3] = 3 and hence x is assigned 3. Again x = 3 and therefore
# the program will get into an infinite loop in the while
# statement.
return "Done"