python - 在 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
解决方案
您的代码中的部分len(qa['answers'][0]['text'])
会引发错误,因为len()
需要一个字符串。您可以通过输入len(3)
python 解释器来验证自己。检查您的数据 qa['answers'] 数组中的 'text' 键是否在某处包含整数值。或者,如果您确实需要整数,请修改这段代码。
我从您提供的原始代码和数据中运行了该部分,并且它在没有抛出错误的情况下进行了解析。既然您提到您使用“类似”数据集,我假设您或其他人修改了内容...
(如果您提供原始数据集和代码会很有帮助)
推荐阅读
- ibm-mq - IBM MQ - 如何独立地将消息出列并提交?
- mysql - FULL_GROUP_BY 有什么不好的吗
- css - 有没有办法在 React Native 中使用 Emmet CSS 缩写?
- python - 提供条件时,While 循环未按预期工作
- python - 我不知道出了什么问题,但是我的 Django 应用程序无法正常工作我正在学习一门新课程,所以请提供任何帮助
- scala - 带有迭代器的 Scala for 循环得到了意想不到的结果
- python - 我使用 pyserial 模块,但只能读取,不能发送数据并阻塞
- python-3.x - 从 Azure 函数(将由 Snowflake 程序使用)发送电子邮件,而不使用任何第三方 API,如 SendGrid
- python - SyntaxError:小饰品 main.py 中第 16 行的错误输入
- c# - WPF 中的调度程序和异步等待