我如何进行这项工作?我正在提取一个int值列表,并尝试将年份添加到列表中。
dataList = []
read = open("USPopulation.txt", 'r')
population = read.readline().rstrip('\n')
year = 1950
i = 0
maxPopulation = 0
minPopulation = sys.maxsize
avgPopulation = 0
total = 0
maxPop_Year = 0
minPop_Year = 0
while population != "":
year += i
dataList[i].append(year)
dataList[i].append(population)
i += 1
population = read.readline().rstrip('\n')
错误
line 8, in <module>
dataList[i].append(year)
IndexError: list index out of range
样本输入
151868
153982
156393
158956
161884
165069
168088
171187
174149
177135
179979
182992
185771
188483
我正在尝试先运行此程序,然后再处理信息输出。但是我打算做的是处理信息,以找到最大的人口数量和最小的人口数量,以及几年之间的平均值,并显示该信息。
for i in range(len(dataList)):
if dataList[i][1] > maxPopulation:
maxPopulation = dataList[i][1]
macPop_Year = dataList[i][0]
if dataList[i][1] < minPopulation:
minPopulation = dataList[i][1]
minPop_Year = dataList[i][0]
print("The year", maxPop_Year, "had the most population with", maxPopulation)
print("The year", minPop_Year, "had the least population with", minPopulation)
错误
if dataList[i][1] > maxPopulation:
TypeError: '>' not supported between instances of 'str' and 'int'
答案 0 :(得分:0)
dataList = []
read = open("USPopulation.txt", 'r')
population = read.readline().rstrip('\n')
year = 1950
i = 0
while population != "":
year += i
#An empty list needs to be append to add items
#fix begin
dataList.append([])
#fix end
dataList[i].append(year)
dataList[i].append(population)
i += 1
population = read.readline().rstrip('\n')
答案 1 :(得分:0)
最小,最大和平均值的完整代码(但使用内联列表而不是文件读取器)
您应该使用哈希表或关联数组而不是列表。
语句year += i
也是不正确的,因为它将使year
以意外的方式增加-1950、1951、1953、1956、1960 ...
dataList = {}
input = [151868,153982,156393,158956,161884,165069,168088,171187,174149,177135,179979,182992,185771, 188483]
year = 1949
min_popl = -1
max_popl = -1
minyr = -1
maxyr = -1
total_popl = 0
i = 0
for popl in input:
year += 1
i += 1
dataList[year] = popl
total_popl += popl
if min_popl == -1 or popl < min_popl:
min_popl = popl
minyr = year
if popl > max_popl:
max_popl = popl
maxyr = year
print("Minimum popl [{}] in year [{}]".format(min_popl, minyr))
print("Maximum popl [{}] in year [{}]".format(max_popl, maxyr))
print("Average popl [{}]".format(total_popl/i))
以上内容的输出-
Minimum popl [151868] in year [1950]
Maximum popl [188483] in year [1963]
Average popl [169709.7142857143]