在Google Colab构建字典时反复遇AttributeError错误求助
解决AttributeError: 'int' object has no attribute 'count'问题
错误的核心原因很明确:你使用的temperatures是一个整数类型变量,而count()是列表、字符串这类可迭代容器才有的方法,整数没有这个属性,所以调用temperatures.count(33)会直接触发报错。
修正步骤:
确保
temperatures是列表(或其他支持count()的可迭代对象)
你需要先定义包含温度数据的列表,比如:temperatures = [33, 34, 39, 40, 42, 29, 33, 34] # 示例温度数据集检查之前的代码,是否不小心把
temperatures赋值成了单个整数(比如temperatures = 33),这会导致后续调用count()失败。优化字典生成代码(可选,但更简洁)
不用逐个手动写每个温度的count()调用,可以用字典推导式简化:target_temps = [33, 34, 39, 40, 42, 29] temp_dict = {str(temp): [temperatures.count(temp)] for temp in target_temps}
内容的提问来源于stack exchange,提问作者Vaishnavi002
相关产品推荐
相关产品推荐

