嵌套for循环中的错误(Python)

时间:2009-09-28 15:05:01

标签: python syntax

我在以下代码中收到错误消息。错误消息为"Error: Inconsistent indentation detected!"

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

如果有任何其他错误,如果有人在这里纠正我,我将非常感激。

感谢。

/吉拉尼

5 个答案:

答案 0 :(得分: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

答案 1 :(得分: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在评论中指出的那样,这更像是pythonic:

s = [30, 40, 50]
for (j, h) in enumerate(s):
    # do stuff here

枚举按顺序返回三对(0,30),(1,40)和(2,50)。有了这个,你可以同时将索引和s以及实际元素放在一起。

答案 2 :(得分:2)

将您的变量初始化为零的三行与其他代码的缩进程度不同。甚至在stackoverflow上显示的代码也显示出来。

另外,请检查您是否没有混合制表符和空格。

答案 3 :(得分:1)

我也认为这是一个标签/空间混合问题。一些编辑器,如Textmate,可以选择显示“隐形”字符,如制表符和换行符。在编写代码时非常方便,特别是在Python中。

答案 4 :(得分:0)

这部分:

    for b in a:
           c=a[b]                                #too much indentation

“c = a [b]”缩进8个空格而不是4个。它只需要4个空格(即一个python缩进)。

Ian是对的,“for x in y”语法与其他语言不同。

list1 = [10, 20, 30]
for item in list1:
    print item

输出将是:“10,20,30”,而不是“1,2,3”。