Python代码报错Unresolved attribute reference 'find_all' for class 'list'如何解决
报错原因
find_all并非Python内置列表(list)的原生方法,该方法通常是BeautifulSoup等网页解析库的对象方法,你将其直接调用在列表类型变量working_days_table上,就会触发属性不存在的报错。
解决方案
要提取列表中所有字典的day字段值,使用列表推导式即可实现,写法简洁高效:
working_days_table = [{"day": 1, "start_at": "09:15", "stop_at": "09:25"}, {"day": 2, "start_at": "09:15", "stop_at": "23:25"}, {"day": 3, "start_at": "09:15", "stop_at": "09:25"}, {"day": 4, "start_at": "09:15", "stop_at": "09:25"}, {"day": 5, "start_at": "09:15", "stop_at": "09:25"}, {"day": 6, "start_at": "13:42", "stop_at": "15:31"} ] if __name__ == '__main__': # 遍历列表所有字典,提取day字段 time_periods = [item["day"] for item in working_days_table] print(time_periods) # 输出:[1, 2, 3, 4, 5, 6]
如果不确定列表中的字典是否都存在day字段,为了避免KeyError,可以做兼容处理:
- 仅保留存在
day字段的字典的对应值:time_periods = [item["day"] for item in working_days_table if "day" in item] - 不存在
day字段时返回默认值None:time_periods = [item.get("day") for item in working_days_table]
内容的提问来源于stack exchange,提问作者user252441
相关产品推荐
相关产品推荐

