问题描述
"""A program to read a CSV file of rainfalls and print the totals
for each month.
"""
from os.path import isfile as is_valid_file
def filename():
"""get's the filename"""
infile = input('Input csv file name? ')
while not is_valid_file(infile):
print('File does not exist.')
infile = input('Input csv file name? ')
return infile
def read_file(file):
"""reads the file"""
datafile = open(file)
data = datafile.read().splitlines()
datafile.close()
return data
def rainfall_parameters(data):
"""organises data into month and num_days and returns a list of
(month,rainfall) tuples"""
results = []
for line in data:
columns = line.split(',')
month = int(columns[0])
num_days = int(columns[1])
total = total_rainfall(columns,num_days)
results.append((month,total))
return results
def total_rainfall(columns,num_days):
"""gets the total rainfall"""
total = 0
for col in columns[2:2 + num_days]:
total += float(col)
return total
def print_results(results):
"""prints the monthly total rainfalls"""
print('Monthly total rainfalls')
for (month,total_rain) in results:
print('Month {:2}: {:.1f}'.format(month,total_rain))
def main():
"""Prompt the user to provide a csv file of rainfall data,process the
given file's data,and print the monthly rainfall totals.
The file is assumed to have the month number in column 1,the number
of days in the month in column 2,and the floating point rainfalls
(in mm) for that month in the remaining columns of the row.
"""
global_file = filename()
global_cols = read_file(global_file)
global_results = rainfall_parameters(global_cols)
print_results(global_results)
main()
解决方法
看起来很奇怪,但是您可以删除几个局部变量:
def rainfall_parameters(data):
"""organises data into month and num_days and returns a list of
(month,rainfall) tuples"""
results = []
for line in data:
columns = line.split(',')
#month = int(columns[0]) # no longer needed
#num_days = int(columns[1]) # no longer needed
total = total_rainfall(columns,int(columns[1])) # move num_days
results.append((int(columns[0]),total)) # move month
return results