微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

我需要rainage_parameters为7条语句,如何从当前的8条中更改特定功能,并且仍然可以使程序正常工作?

如何解决我需要rainage_parameters为7条语句,如何从当前的8条中更改特定功能,并且仍然可以使程序正常工作?

"""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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。