python - 无法找到IndexError的解决方案:列表索引超出范围

时间:2017-12-24 02:20:59

标签: python arrays loops indexing index-error

错误是:

File "node2.py", line 96, in put_chains_together
    if outer_index > 0 and (chain['chain'][0]['index'] - prev_chain['chain'][-1]['index'] != 1):
IndexError: list index out of range

以下是相关代码:

    all_chains = []
    prev_chain = {}
    for outer_index, chain in enumerate(chains_to_add):
        print('\n //// chain in chains_to_add')
        pprint(chain)
        if outer_index > 0 and (chain['chain'][0]['index'] - prev_chain['chain'][-1]['index'] != 1):
            r = requests.get("http://" + connections[len(connections) -1]['ip'] + ":" + connections[len(connections) - 1]['port'] + "/give_chain", params = {'previous': prev_chain['chain'][0]['previous_hash'], 'start_at_index':0, 'increment_by':len(prev_chain['chain']) + 1})
            chains_from_request = json.loads(r.text)
            del all_chains[-len(chains_from_request['chain'])]
            for index, ch in enumerate(chains_from_request['chain']):
                all_chains.append(ch)

        prev = {}
        for index, ch in enumerate(chain['chain']):
            deleted = False
            if index > 0 and ch['index'] == prev['index']:
                if ch['timestamp'] < prev['timestamp']:
                    del chain['chain'][index - 1]
                    deleted = True
                else:
                    del chain['chain'][index]
                    deleted = True

            if not deleted: 
                all_chains.append(ch)

            prev = ch

        prev_chain = chain

我无法弄清楚错误指的是哪个索引...我认为它是chain[0]['index']因为另一个索引只是一个指令来获取最后一个不应该给出的块列表索引错误。 chain['chain']prev_chain['chain'](只是chain['index']的副本)都是包含对象的数组。每个对象都有一个索引。感谢

0 个答案:

没有答案