首页 > 解决方案 > 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'

标签: stringobjectattributes

解决方案


在同一个范围内不能有两个同名的变量。要么malelife是列表,要么是字符串;它不能同时是"John"两者[]。您想将malelife字符串附加到malelife列表中;但实际上只有一个malelife,而且当时是一个字符串。重命名其中一个(类似于femalelife),问题就会消失。

请注意,讲师有不同的变量名称;这两个版本您声称的不同。你的“缩短”是问题所在。如果一个版本有效而​​另一个无效,您应该查看您所做的更改以找出问题所在。


推荐阅读