Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/loops/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python while循环在超出范围(0,10)后不会终止,但for循环会终止。为什么呢?_Python_Loops - Fatal编程技术网

Python while循环在超出范围(0,10)后不会终止,但for循环会终止。为什么呢?

Python while循环在超出范围(0,10)后不会终止,但for循环会终止。为什么呢?,python,loops,Python,Loops,如果我对下面的代码使用while循环,它永远不会继续打印我的列表命令,但如果我只更改while to,它将按预期工作-在shell的一行中打印所有公共整数 a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89] b = [1, 1, 2, 3, 5, 6, 7, 8, 9, 10, 11, 12, 13] x = 0 Comm = [] #common int in both lists while x in range(0,len(a)): if a

如果我对下面的代码使用while循环,它永远不会继续打印我的列表命令,但如果我只更改while to,它将按预期工作-在shell的一行中打印所有公共整数

a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
b = [1, 1, 2, 3, 5, 6, 7, 8, 9, 10, 11, 12, 13]

x = 0

Comm = [] #common int in both lists

while x in range(0,len(a)):
    if a[x] in b:
        Comm.append(a[x])
        x += 1
print(Comm)
您应该使用for循环而不是while

如果x从0到6,那么a[6]=13。a[6]在b中,因此x变成7,a[7]=21


a[7]不在b中,因此x不会增加。这意味着x在7处停止,不会脱离while循环。

您是否打算将x+=1置于if条件下?如果没有该条件,x是否会在while循环中增加?x不会增加。我想你的意思是使用for循环,即rangelena:中的x,然后删除x+=1这是一种很糟糕的编写方法,会导致你看到的类型或错误。只需在a中使用n,而忘记所有的索引。然后你可以在b中使用if n和appendn。更好的是,使用一个集合交集,您可以使用Comm=listseta.intersectionbRight这样的东西来完全放松循环,您通常可以不处理Python中的索引,这使得许多事情更容易推理,许多错误更容易避免。