基本上我在写一个程序,读取一个文本文件,并将文件中的每一行放入一个列表中。该文件列出了1950-1990年间美国的人口,以千为单位。然而,这个文件没有列出年份,所以我需要我的程序在每个人口数字上标注一年。你知道吗
我的任务是:
“你要写一个程序(命名为Analysis_人口.py)将上述文件的内容读入列表,并计算和显示:
1950年至1990年(含)人口年平均变化
1950-1990年(含)人口增长最快的年份
1950-1990年(含)人口增长最小的年份“
除了年份标签,我什么都能用。你知道吗
我的代码如下:
year = 1950
with open("USPopulation.txt", "r") as f:
popList = [line.strip() for line in f]
popList = [ int(x) for x in popList ]
for x in popList:
year = year + 1
diff = [abs(j-i) for i,j in zip(popList, popList[1:])]
maxDiff = max(abs(x - y) for (x, y) in zip(popList[1:], popList[:-1]))
minDiff = min(abs(x - y) for (x, y) in zip(popList[1:], popList[:-1]))
print("The average annual change in population during the time period 1950 - 1990 is:\n",
(sum(diff)/len(diff)))
print("\nThe year with the greatest increase in population during the time period 1950 - 1990 is:",
year, "-", year + 1, "with an increase of", maxDiff, "people.")
minDiff = min(abs(x - y) for (x, y) in zip(popList[1:], popList[:-1]))
print("\nThe year with the smallest increase in population during the time period 1950 - 1990 is:",
year, "-", year + 1, "with an increase of", minDiff, "people.")
我得到的结果是:
The average annual change in population during the time period 1950 - 1990 is:
2443.875
The year with the greatest increase in population during the time period 1950 - 1990 is: 1991 - 1992 with an increase of 3185 people.
The year with the smallest increase in population during the time period 1950 - 1990 is: 1991 - 1992 with an increase of 1881 people.
如您所见,它每次都输出相同的、不正确的年份。 任何帮助纠正这一点将不胜感激。你知道吗
目前没有回答
相关问题 更多 >
编程相关推荐