Python报错:TypeError: list indices must be integers or slices, not str

编程入门 行业动态 更新时间:2024-10-19 22:38:27

Python<a href=https://www.elefans.com/category/jswz/34/1771188.html style=报错:TypeError: list indices must be integers or slices, not str"/>

Python报错:TypeError: list indices must be integers or slices, not str

问题概述

首先报错信息的字面意思为,类型错误:列表索引必须是整数或切片,而不是str
代码如下

# 人体行为信息
person_info = items['person_info']
# 行为信息属性
attributes = person_info['attributes']print(person_info)
print(attributes)

person_info如下

[{'attributes': {'both_hands_leaving_wheel': {'score': 0.12176866084337, 'threshold': 0.75}, 'eyes_closed': {'score': 0.47068807482719, 'threshold': 0.55}, 'no_face_mask': {'score': 0.99440461397171, 'threshold': 0.75}, 'not_buckling_up': {'score': 0.40850603580475, 'threshold': 0.44}, 'smoke': {'score': 0.0083957426249981, 'threshold': 0.48}, 'cellphone': {'score': 0.2926022708416, 'threshold': 0.69}, 'not_facing_front': {'score': 0.6774777173996, 'threshold': 0.5}, 'yawning': {'score': 0.0052815575618297, 'threshold': 0.5}, 'head_lowered': {'score': 0.18483714014292, 'threshold': 0.55}}, 'location': {'score': 0.97045028209686, 'top': 37, 'left': 64, 'width': 244, 'height': 207}}]

报错信息如下

分析原因

列表中嵌套了字典,然后字典中也嵌套了字典,为了区分要取列表中的哪个字典,取值的时候要加字典数据的位置索引也就是下标,比如0,1,2之类
,然后加key值,就可以取出想要的数据值了

解决办法

# 人体行为信息
person_info = items['person_info']
# 行为信息属性
attributes = person_info[0]['attributes']print(person_info)
print(attributes)

成功取出attributes如下

{'both_hands_leaving_wheel': {'score': 0.12176866084337, 'threshold': 0.75}, 'eyes_closed': {'score': 0.47068807482719, 'threshold': 0.55}, 'no_face_mask': {'score': 0.99440461397171, 'threshold': 0.75}, 'not_buckling_up': {'score': 0.40850603580475, 'threshold': 0.44}, 'smoke': {'score': 0.0083957426249981, 'threshold': 0.48}, 'cellphone': {'score': 0.2926022708416, 'threshold': 0.69}, 'not_facing_front': {'score': 0.6774777173996, 'threshold': 0.5}, 'yawning': {'score': 0.0052815575618297, 'threshold': 0.5}, 'head_lowered': {'score': 0.18483714014292, 'threshold': 0.55}}

更多推荐

Python报错:TypeError: list indices must be integers or slices, not str

本文发布于:2024-02-11 11:49:34,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1680835.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:报错   list   TypeError   Python   slices

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!