gpt4 book ai didi

python - 将功能分解为更易于管理的部分

转载 作者:行者123 更新时间:2023-12-01 05:44:50 25 4
gpt4 key购买 nike

我现在有一个计划,我正在尝试将其分解为更小、更易于管理的部分以用于锻炼目的。但问题是,我在遵循所设定的指导方针时遇到了一些困难。值得注意的是,一个函数不能包含超过 6 个语句。

这是程序最初的样子..

def print_monthly_totals (input_csv_filename):
'''Read the given CSV file and print the totals for each month.
The input 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 each month in the remaining columns
of the row.
'''
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))

print_monthly_totals('rainfalls2011.csv')

我设法将其分解为两个单独的函数,给了我..

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])
trf = rainfall_total(columns, num_days)
print('Month {:2}: {:.1f}'.format(month, trf))

def rainfall_total(columns, num_days):
total_rainfall = 0
for col in columns[2 : 2 + num_days]:
total_rainfall += float(col)
return total_rainfall

print_monthly_totals('rainfalls2011.csv')

但是我的 print_monthly_totals 函数仍然太大,我需要创建第三个函数来满足每个函数 6 个语句的规则。我刚刚的尝试导致了一系列全局名称未定义的错误..

def print_monthly_totals(input_csv_filename):
data = open(input_csv_filename).readlines()
print('Rainfall totals for each month')
trf = rainfall_total(columns, num_days)
print('Month {:2}: {:.1f}'.format(month, trf))

def data():
for line in data:
columns = line.split(',')
month = int(columns[0])
num_days = int(columns[1])

def rainfall_total(columns, num_days):
'''Guts of the program'''
total_rainfall = 0
for col in columns[2 : 2 + num_days]:
total_rainfall += float(col)
return total_rainfall

print_monthly_totals('rainfalls2011.csv')

任何帮助将不胜感激,干杯!

最佳答案

这个怎么样:

def print_monthly_totals(input_csv_filename):
with open(input_csv_filename) as csv_file:
data = csv_file.readlines()
print('Rainfall totals for each month')
for line in data:
manage_line(line)


def manage_line(line):
columns = line.split(',')
month = int(columns[0])
num_days = int(columns[1])
trf = rainfall_total(columns, num_days)
print('Month {:2}: {:.1f}'.format(month, trf))

def rainfall_total(columns, num_days):
total_rainfall = 0
for col in columns[2 : 2 + num_days]:
total_rainfall += float(col)
return total_rainfall

print_monthly_totals('rainfalls2011.csv')

这听起来非常接近您可能想要的。希望对您有所帮助。

关于python - 将功能分解为更易于管理的部分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16415759/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com