String 属性错误:';str';对象没有属性';附加';。。。为讲师工作
我看过其他关于同一问题的帖子,但找不到答案。我的代码与在线课程完全相同(都在下面,但我确实缩短了目录)。为什么它对老师有效而对我无效String 属性错误:';str';对象没有属性';附加';。。。为讲师工作,string,object,attributes,String,Object,Attributes,我看过其他关于同一问题的帖子,但找不到答案。我的代码与在线课程完全相同(都在下面,但我确实缩短了目录)。为什么它对老师有效而对我无效 下面是我的代码: from matplotlib import pyplot data = open("lifeexpectanciesusa.txt", "r").readlines() dates = [ ] malelife = [ ] femalelife = [ ] for line in data: date, malelife, f
下面是我的代码:
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'
pyplot.show()
回溯(最近一次呼叫最后一次):
文件“”,第12行,在
malelife.append(malelife)
AttributeError:“str”对象没有属性“append”
同一范围内不能有两个同名变量。malelife
要么是一个列表,要么是一个字符串;它不能同时是“John”
和[]
。您希望将malelife
字符串附加到malelife
列表中;但事实上,只有一个malelife
,当时它是一个字符串。重命名其中一个(类似于femalelife
)问题就会消失
注意讲师有不同的变量名;这两个版本与您声称的不同。你的“缩短”就是问题所在。如果一个版本有效,而另一个版本无效,您应该查看您所做的更改,以找出问题所在。嘿,阿玛丹,我刚刚看到……在花费了将近一个小时之后。看看代码!我正在试图删除这篇文章,所以我看起来不太傻!不用担心,每个人偶尔都会有一个大脑屁,我尤其是我自己…但有趣的是…教授们有一个指数分布,而我的分布是非常线性的。这是一个不同的问题,请这样问(在尝试自己计算之后)。