Python - 嵌套for循环和索引超出范围

时间:2016-07-20 09:47:19

标签: python list loops for-loop nested

我是Python的新手,在使用嵌套for循环时遇到以下错误

IndexError: list index out of range

这是我的代码

count = 0
count2 = 1
rlength = range(len(records))
for i in rlength:
    ex = records[count].id
    for bla in rlength:
        if re.search(ex, records[count2].id) != None:
            print records[count2].id
        count2 += 1
    count += 1
    count2 = count + 1

编辑:

使用以下代码修复

rlength = range(len(records))
for i in rlength:
    ex = records[i].id
    for bla in rlength:
        if bla + 1 < len(rlength) and re.search(ex, records[bla + 1].id) != None:
            print records[bla].id

2 个答案:

答案 0 :(得分:1)

如果我了解您要执行的操作,我们根本不确定您是否需要countcount2。我想你可以使用循环生成的数字。我建议使用enumerate()代替range(len())

for i1,rlength1 in enumerate(records):
    ex = rlength1.id
    for i2,rlength2 in enumerate(records):
        if re.search(ex, rlength2.id) != None:
            print rlength2.id

答案 1 :(得分:0)

i=1的循环失败。为什么? 当i=1, count2 = 2 (= count + 1, and count = 0+1 = 1)
在内循环中,count2 goes from 2 to 2+len(records)-1-1(因为我们在查看值后递增)= len(records)
但是没有records[len(records)](并且超出范围的索引在python中不等于None!)