我想将它分成几个较小的函数,以使它看起来更整洁,更容易阅读,但每当我尝试这个时,我似乎无法让它工作。任何帮助将不胜感激。
目前我的代码看起来像这样
def print_monthly_totals (input_csv_filename):
data = open(input_csv_filename).readlines()
print('Rainfall totals for each month')
for line in data:
columns = line.split(',')
month = int(columns[0])
num_days = int(columns[1])
total_rainfall = 0
for col in columns[2 : 2 + num_days]:
total_rainfall += float(col)
print('Month {:2}: {:.1f}'.format(month, total_rainfall))
我希望它看起来更像下面的例子
def print_monthly_totals (input_csv_filename):
data = open(input_csv_filename).readlines()
print('Rainfall totals for each month')
def SOMETHING(SOMETHING): #The SOMETHING is just a filler
for line in data:
columns = line.split(',')
month = int(columns[0])
num_days = int(columns[1])
total_rainfall = 0
def SOMETHING(SOMETHING): #The SOMETHING is just a filler
for col in columns[2 : 2 + num_days]:
total_rainfall += float(col)
print('Month {:2}: {:.1f}'.format(month, total_rainfall))
答案 0 :(得分:1)
你可以像这样缩短你的功能:
def print_monthly_totals (input_csv_filename):
data = open(input_csv_filename).readlines()
print('Rainfall totals for each month')
for line in data:
columns = line.split(',')
month, num_days = int(columns[0]), int(columns[1])
daily_rainfalls = [float(x) for x in columns[2:2+num_days]]
total_rainfall = sum(daily_rainfalls)
print('Month {:2}: {:.1f}'.format(month, total_rainfall))
或者将它分成两个函数:
def line_to_rainfall(line):
cols = line.split(",")
month, num_days = int(cols[0]), int(cols[1])
daily_rainfalls = [float(x) for x in cols[2:2+num_days]]
return month, daily_rainfalls
def print_monthly_totals (input_csv_filename):
data = open(input_csv_filename).readlines()
print('Rainfall totals for each month')
for line in data:
month, daily_rainfalls = line_to_rainfall(line)
total_rainfall = sum(daily_rainfalls)
print('Month {:2}: {:.1f}'.format(month, total_rainfall))
答案 1 :(得分:0)
我能想到的最合理的分割功能将数据读取逻辑与打印逻辑分开:
def print_monthly_totals (input_csv_filename):
months, rainfall_totals = get_rainfall_data(input_csv_filename)
print('Rainfall totals for each month')
for month, total_rainfall in zip(months, rainfall_totals):
print('Month {:2}: {:.1f}'.format(month, total_rainfall))
def get_rainfall_data(input_csv_filename):
data = open(input_csv_filename) # .readlines() isn't necessary
months = []
rainfall_totals = []
for line in data:
columns = line.split(',')
month = int(columns[0])
months.append(month)
num_days = int(columns[1])
total_rainfall = 0
for col in columns[2 : 2 + num_days]:
total_rainfall += float(col)
rainfall_totals.append(total_rainfall)
return months, rainfall_totals