首页 > 解决方案 > 在 Python 中的字典列表中使用 for 循环时键入错误

问题描述

在解析 json 文件中的数据时,在 Python 3.6 上使用该结构时出现错误:

for topic in data:
    cqas = [{'context':      paragraph['context'],
            'id':           qa['id'],
            'question':     qa['question'],
            'answer':       qa['answers'][0]['text'],
            'answer_start': qa['answers'][0]['answer_start'],
            'answer_end':   qa['answers'][0]['answer_start'] + \
                            len(qa['answers'][0]['text']) - 1,
            'topic':        topic['title'] }
            for paragraph in topic['paragraphs']
            for qa in paragraph['qas']]

如上所述,我找不到有关在字典列表中使用 for 循环的文档。我想学习它,因为在使用该结构时我也会收到一条错误消息:

在此处输入图像描述

数据集:https ://raw.githubusercontent.com/YerevaNN/R-NET-in-Keras/master/data/dev-v1.1.json

标签: pythonjsonlistparsingdictionary

解决方案


您的代码中的部分len(qa['answers'][0]['text'])会引发错误,因为len()需要一个字符串。您可以通过输入len(3)python 解释器来验证自己。检查您的数据 qa['answers'] 数组中的 'text' 键是否在某处包含整数值。或者,如果您确实需要整数,请修改这段代码。

我从您提供的原始代码和数据中运行了该部分,并且它在没有抛出错误的情况下进行了解析。既然您提到您使用“类似”数据集,我假设您或其他人修改了内容...

(如果您提供原始数据集和代码会很有帮助)


推荐阅读