0
我想將它分成幾個較小的函數,以使它看起來更整潔,更易於閱讀,但是每當我嘗試這個時,我似乎都無法使它工作。任何幫助,將不勝感激。Python更多功能
目前我的代碼看起來像這樣
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))
個人而言,我不認爲你目前的功能實在是太漫長,但是當你分手了一個功能,它往往是最好的把它分解成單獨的任務。你目前的功能達到什麼樣的任務? – Marius 2013-05-09 02:04:16
使用這個簡短的函數可能會更好,在每個部分的開始處添加註釋行,以解釋這些函數的功能。 – Marius 2013-05-09 02:06:41
這似乎是一個更適合[codereview.se]的問題。 – nneonneo 2013-05-09 02:16:05