【发布时间】:2016-07-20 09:47:19
【问题描述】:
我对 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
【问题讨论】:
-
我认为这里是问题记录[count2].id),你在其中向前迈进了一步。
-
我认为您必须将此行从 if re.search(ex, records[count2].id) != None: 更改为 if count2 in records and re.search(ex, records[count2 ].id) != 无:
-
count2 可以达到我们的范围。你想做什么?
-
我认为你根本不需要
count和count2。您可以只使用i和bla代替,您的 for 循环将始终保持在该范围内。 -
谢谢,我想这已经成功了
标签: python list loops for-loop nested