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

Gil*_*ani 1 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
Run Code Online (Sandbox Code Playgroud)

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

谢谢.

/吉拉尼

Sil*_*ost 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
Run Code Online (Sandbox Code Playgroud)

否则你会有IndexError.


Ian*_*and 5

SilentGhost是正确的 - 与Javascript之类的语言不同,当你写作时

s = [30, 40, 50]
for j in s:
Run Code Online (Sandbox Code Playgroud)

然后j不分配0,1和2 - 它被赋予实际值30,40和50.所以没有必要说,在另一条线上,

h = s[j]
Run Code Online (Sandbox Code Playgroud)

事实上,如果你这样做,第一次通过循环,它将评估为

h = s[30]
Run Code Online (Sandbox Code Playgroud)

哪个超出了三元素列表的界限,你会得到一个IndexError.

如果你真的想以另一种方式去做 - 如果你真的需要索引以及值,你可以这样做:

s = [30, 40, 50]
for j in range(len(s)):
    h = s[j]
Run Code Online (Sandbox Code Playgroud)

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
Run Code Online (Sandbox Code Playgroud)

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

  • 如果他需要索引和值,他应该使用`enumerate`. (7认同)