Python-按年份标记列表中的项目

时间:2017-04-07 18:20:34

标签: python

基本上我正在编写一个程序来读取文本文件并将文件中的每一行放入一个列表中。该文件列出了1950年至1990年期间美国的数千人口。然而,该文件没有列出年份,因此我需要我的程序用一年标记每个人口编号。

我的任务是:

"您要编写一个程序(将其命名为Analysis_population.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.

如您所见,每次输出相同,不正确的年份。 任何帮助纠正这一点将不胜感激。

Here is a link to the text file

0 个答案:

没有答案