Python中嵌套for循环的错误
我在下面的代码中遇到了一个错误。错误信息是 "错误:检测到不一致的缩进!"
s=[30,40,50]
a=[5e6,6e6,7e6,8e6,8.5e6,9e6,10e6,12e6]
p=[0.0,0.002,0.004,0.006,0.008,0.01,0.015,0.05,0.1,0.15,0.2]
j=0
b=0
x=0
for j in s:
h=s[j]
print "here is the first loop" +h
for b in a:
c=a[b] #too much indentation
print"here is the second loop" +c #too much indentation
for x in p: #too much indentation
k=p[x]
print"here is the third loop" +k
如果还有其他错误的话,我会非常感激这里的任何人能帮我纠正。
谢谢。
/Gillani
5 个回答
2
你用来把变量初始化为零的那三行代码缩进和其他代码不一样。连在StackOverflow上显示的代码也能看出来。
另外,检查一下你有没有把制表符和空格混在一起使用。
5
SilentGhost说得对——和JavaScript这样的语言不同,当你写
s = [30, 40, 50]
for j in s:
时,j并不是被赋值为0、1和2,而是被赋值为实际的值30、40和50。所以在另一行中没有必要再写
h = s[j]
事实上,如果你这样做,第一次循环时,它会计算为
h = s[30]
这对于一个只有三个元素的列表来说是超出范围的,你会遇到一个IndexError(索引错误)。
如果你真的想以另一种方式做——如果你真的需要索引和对应的值,你可以这样做:
s = [30, 40, 50]
for j in range(len(s)):
h = s[j]
len(s)会给你s的长度(在这个例子中是3),而range函数会为你生成一个新列表,range(n)包含从0到n-1的整数。在这个例子中,range(3)返回[0, 1, 2]
正如SilentGhost在评论中提到的,这种写法更符合Python的风格:
s = [30, 40, 50]
for (j, h) in enumerate(s):
# do stuff here
enumerate(s)会返回三个配对(0, 30)、(1, 40)和(2, 50),按这个顺序。这样,你就可以同时获得s的索引和实际的元素。
6
一旦你整理好了你的缩进(也就是说,你的代码里要么只用制表符,要么只用空格),接下来你需要修正你的循环:
s = [30,40,50]
a = [5e6,6e6,7e6,8e6,8.5e6,9e6,10e6,12e6]
p = [0.0,0.002,0.004,0.006,0.008,0.01,0.015,0.05,0.1,0.15,0.2]
for j in s: # within loop j is being 30 then 40 then 50, same true for other loops
print "here is the first loop" + j
for b in a:
print"here is the second loop" + b
for x in p:
print"here is the third loop" + x
否则你会遇到IndexError
错误。