Python index error: How to debug

Python index error: How to debug

我有以下代码:

import csv
import sys

with open('zone1.txt', 'r') as z1:
    zone1 = z1.readlines()

with open('Derived_Dataset.csv', 'r') as ud:
    UMC_Data = ud.readlines()

no_rows = 0

for row1 in zone1:
    for row2 in UMC_Data:
        if row1.split(",")[2] == row2.split(",")[2] and row1.split(",")[3] == row2.split(",")[3]:
            print(row2)
            no_rows = no_rows = 1

print('\n')
print(no_rows)

我得到的索引错误如下:

    Traceback (most recent call last):
  File "C:/Users/gakadam/PycharmProjects/waferZoning/main.py", line 14, in <module>
    if row1.split(",")[2] == row2.split(",")[2] and row1.split(",")[3] == row2.split(",")[3]:
IndexError: list index out of range

由于两个文件都很大,通常的调试选项(JetBrains)不可行。是否有调试器可以有效地帮助我缩小哪些变量超出其限制?谢谢。

按如下方式重写您的 for 循环:

for iIdx1, row1 in enumerate(zone1):
    lsSplitted = row1.split(",")
    assert(len(lsSplitted) >= 4), "Error in row1 line no {} line {}".format(iIdx1, str(row1))
    for iIdx2, row2 in enumerate(UMC_Data):
        lsRow2Splitted row2.split(",")
        assert(len(lsRow2Splitted) >= 4), "Error in row2 line no {} line {}".format(iIdx2, str(row2))
        if (lsSplitted[2] == lsRow2Splitted[2] and 
            lsSplitted[3] == lsRow2Splitted[3]):
            print(row2)
            no_rows = no_rows = 1

我认为断言将帮助您找出出现索引错误的行。