string - AttributeError: 'str' object has no attribute 'append'...适用于教师
问题描述
我已经查看了有关同一问题的其他帖子,但找不到答案。我的代码与在线课程完全一样(两者都在下面,但我确实缩短了目录)。为什么它适用于教练而不是我?
下面是我的代码:
from matplotlib import pyplot
data = open("lifeexpectanciesusa.txt", "r").readlines()
dates = [ ]
malelife = [ ]
femalelife = [ ]
for line in data:
date, malelife, femalelife = line.split(",")
dates.append(date)
malelife.append(malelife)
femalelife.append(femalelife)
pyplot.plot(dates, malelife,"bo-", label="Men")
pyplot.plot(dates, femalelife, "mo-", label="Female")
pyplot.legend(loc="upper left")
pyplot.xlabel("Year")
pyplot.ylabel("Age")
pyplot.title("Life Expectancies for men and woman in the USA over time")
pyplot.show()
以下是讲师所拥有的: 讲师代码
我得到的错误信息是:
pyplot.show()
Traceback (most recent call last):
File "<ipython-input-56-0283726
068cb>", line 12, in <module>
malelife.append(malelife)
AttributeError: 'str' object has no attribute 'append'
解决方案
在同一个范围内不能有两个同名的变量。要么malelife
是列表,要么是字符串;它不能同时是"John"
两者[]
。您想将malelife
字符串附加到malelife
列表中;但实际上只有一个malelife
,而且当时是一个字符串。重命名其中一个(类似于femalelife
),问题就会消失。
请注意,讲师有不同的变量名称;这两个版本与您声称的不同。你的“缩短”是问题所在。如果一个版本有效而另一个无效,您应该查看您所做的更改以找出问题所在。
推荐阅读
- c - 有没有办法可以防止 C 中的 EOF?
- python-3.x - 在 Python FastAPI 中缓存上传的图像以将其上传到雪花
- r - 对包含积分的函数进行积分
- excel - 使用 PowerShell 从 Excel 中读取带有 % 的值
- java - 如何使用 openapi-generator-maven-plugin 生成没有属性的基本模型类
- flutter - Flutter,如何从对象列表中创建 json?
- redis - 是否可以使用 Redis 消除数据丢失?
- python - 将 Pycharm 项目移动到另一个目录
- django - Django 迁移错误:返回 self.cursor.execute(sql, params) django.db.utils.ProgrammingError:
- angular - 如何在离子的同一页面中调整模态的大小?