【发布时间】:2017-12-31 19:44:02
【问题描述】:
我的目标是遍历classes 中的每个 元素,并将classes 中的class 的值添加到一个新列表中。
JSON 结构:
{
"images": [
{
"classifiers": [
{
"classes": [
{
"class": "street",
"score": 0.846
},
{
"class": "road",
"score": 0.85
}
]
}
]
}
]
}
在上述 JSON 示例中,新列表应包含:
{'street','road'}
我尝试迭代 json_data['images'][0]['classifiers']['classes'] 并为每个 list.append() 迭代 class 的值。
list = list()
def func(json_data):
for item in json_data['images'][0]['classifiers']['classes']:
list.append(item['class'])
return(list)
我收到了TypeError,即:
TypeError: list indices must be integers or slices, not str
我从这个TypeError 得到的是它试图将一个字符串添加到列表中,但list.append() 不接受一个字符串作为参数。我需要以某种方式将字符串转换为其他内容。
我的问题是我应该将字符串转换成什么,以便list.append() 接受它作为参数?
【问题讨论】:
-
感谢您向我们展示您的输入和预期输出。现在向我们展示您为此编写的代码,并说明您遇到的问题。
-
我不断收到 TypeError: list indices must be integers or slices, not str 并使用该错误并在 StackOverflow 上尝试修复该错误不起作用。
-
请将完整的回溯也包含在编辑中。
-
classifiers和classes也是列表。json_data['images'][0]['classifiers'][0]['classes']: -
return set(lst)我想。如果这是你所期望的,我会尝试在我的手机上写一个答案——总是很有趣——所以你可以关闭它。
标签: python json python-3.x dictionary typeerror