我是python的新手,我正在用python编写一个程序,该程序将获取日期和汽油价格的列表,并返回一年中每个月的平均值。我现在拥有的代码在第二个月到上个月停止,我不知道为什么。我知道可能有一种更有效的编写方法,因此任何有关此的建议也将有所帮助。任何事情都会有所帮助!谢谢。
def readGasPrices(fileName):
gasFile = open(fileName, 'r')
gasFileList = gasFile.readlines()
priceList = []
for line in gasFileList:
priceList.append(line[11:].rstrip('\n'))
gasFile.close
return priceList
def readGasDates(fileName):
gasFile = open(fileName, 'r')
gasFileList = gasFile.readlines()
dateList = []
for line in gasFileList:
dateList.append(line[0:10])
gasFile.close
return dateList
def average_price_per_month(dates,prices):
month = ''
year = ''
counter = 0
accumulator = 0
for index in range(len(dates)):
if year == '':
year = dates[index][6:10]
currentYear = year
elif month == '':
month = dates[index][0:2]
print('Gas price averages for', currentYear)
print('Month'.center(22) + 'Average'.center(12))
print('====='.center(22) + '======='.center(12))
elif dates[index][0:2] == month and dates[index][6:10] == currentYear:
accumulator += float(prices[index])
counter += 1
elif year != currentYear:
currentYear = year
print()
print('Gas price averages for', currentYear)
print('Month'.center(22) + 'Average'.center(12))
print('====='.center(22) + '======='.center(12))
else:
if month == '01':
month = 'January'
elif month == '02':
month = 'February'
elif month == '03':
month = 'March'
elif month == '04':
month = 'April'
elif month == '05':
month = 'May'
elif month == '06':
month = 'June'
elif month == '07':
month = 'July'
elif month == '08':
month = 'August'
elif month == '09':
month = 'September'
elif month == '10':
month = 'October'
elif month == '11':
month = 'November'
elif month == '12':
month = 'December'
average = accumulator / counter
print(month.ljust(10).center(25) + \
format(average,'.2f').center(0))
counter = 1
accumulator = float(prices[index])
year = dates[index][6:10]
month = dates[index][0:2]
def main():
fileName = input('Enter the file name: ')
gasPriceList = readGasPrices(fileName)
dateList = readGasDates(fileName)
average_price_per_month(dateList, gasPriceList)
main()