Python列表索引超出范围,仅限于大规模迭代

2024-03-29 14:30:27 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个很大的文本文件,
其中每一行都是根据define语法(这是用regex处理的)。你知道吗

我得到以下错误:

remainder = '{} {} '.format(*pieces[-1])
IndexError: list index out of range

在此代码上:

def open_delimited(filename, args):
    with open(filename, args, encoding="UTF-16") as infile:
        chunksize = 10000
        remainder = ''
        for chunk in iter(lambda: infile.read(chunksize), ''):
            pieces = re.findall(r"(\d+)\s+(\d+_\d+)\s+(((post)\s+1)|((\d+_\d+_\d+)\s+(comment)\s+2))(.+)(\d{4}-\d{2}-\d{2})\s+(\d{2}:\d{2}:\d{2})(.*)", remainder + chunk, re.IGNORECASE)
            for piece in pieces[:-1]:
                yield piece
            remainder = '{} {} '.format(*pieces[-1])
        if remainder:
            yield remainder


filename = 'data/AllData_2000001_3000000.txt'

for chunk in open_delimited(filename, 'r'): 
    for j in range(len(chunk)):
        print(chunk[j])

当我限制迭代次数时,代码运行良好。你知道吗

i = 0
for chunk in open_delimited(filename, 'r'): 
    if (i <= 1000):
        for j in range(len(chunk)):
            print(chunk[j])
    else:
        break
    i += 1

Tags: inreformatforpieceargsrangeopen
2条回答

有没有可能pieces是空的?你知道吗

>>> [][-1]
IndexError: list index out of range

我最好的猜测是re.findall有时找不到任何东西。你知道吗

如果正则表达式没有在块中找到一个片段,它将返回一个空列表,从而返回错误。你知道吗

>>> pieces = []
>>> pieces[-1]

IndexError: list index out of range

如果你希望在每一个块中找到一个片段,那么下一个问题是为什么你不能在一个特定的块中找到一个片段。我将继续调试如下

try:
    remainder = '{} {} '.format(*pieces[-1]) 
except IndexError:
    print pieces
    print chunk
    raise

相关问题 更多 >