【问题标题】:Python - nested for loops and index out of rangePython - 嵌套for循环和索引超出范围
【发布时间】: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 可以达到我们的范围。你想做什么?
  • 我认为你根本不需要countcount2。您可以只使用 ibla 代替,您的 for 循环将始终保持在该范围内。
  • 谢谢,我想这已经成功了

标签: python list loops for-loop nested


【解决方案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

【讨论】:

  • 这很有帮助,尽管我实现计数的原因是因为我想将记录 x 与 x+1、x+2、...而不是它本身进行比较。但这为我指明了正确的方向。谢谢
  • @Thistle19 您当然可以执行records[i]records[i+1]records[i+2] 之类的操作,但如果您这样做,您需要在通过它之前停止循环以避免@987654329 @,可以使用 range(len(records)-2) 之类的东西,也可以使用 if i+1 == len(records): break
【解决方案2】:

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!)

【讨论】:

    猜你喜欢
    • 2013-11-25
    • 1970-01-01
    • 2021-09-02
    • 2020-07-23
    • 1970-01-01
    • 1970-01-01
    • 2022-06-13
    • 2019-04-17
    • 1970-01-01
    相关资源
    最近更新 更多