Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
299 views
in Technique[技术] by (71.8m points)

python - How to not hardcode function in this example

The following links contain 2 csv files that the function should pass through grades_1e_2a grades_2e_4a

However my function is only able to pass the 2nd linked file, as it is hardcoded to range(4,8). output: [91.5, 73.5, 81.5, 91.5] The input file will start at the 4th element but may not necessarily end at the 8th element.

def class_avg(open_file):
    '''(file) -> list of float
    Return a list of assignment averages for the entire class given the open
    class file. The returned list should contain assignment averages in the
    order listed in the given file.  For example, if there are 3 assignments
    per student, the returned list should 3 floats representing the 3 averages.
    '''
    marks=[[],[],[],[]]
    avgs = []
    for line in open_file:
        grades_list = line.strip().split(',')
        for idx,i in enumerate(range(4,8)):
            marks[idx].append(float(grades_list[i]))
    for mark in marks:
        avgs.append(float(sum(mark)/(len(mark))))
    return avgs

How do I fix this so that my code will be able to read both files, or any file? I have already opened the file and iterated past the first line with file.readline() in a previous function on the same file. Thanks for everyone's help in advance.

Updated progress: https://gyazo.com/064dd0d695e3a3e1b4259a25d1b0b1a0

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

As both sets of your data start the same place the following works for idx,i in enumerate(range(4,len(grades_list))):

This should fulfill all requirements that Im aware of up to this point

def class_avg(open_file):
    '''(file) -> list of float
    Return a list of assignment averages for the entire class given the open
    class file. The returned list should contain assignment averages in the
    order listed in the given file.  For example, if there are 3 assignments
    per student, the returned list should 3 floats representing the 3 averages.
    '''
    marks = None
    avgs = []
    for line in open_file:
        grades_list = line.strip().split(',')
        if marks is None:
            marks = []
            for i in range(len(grades_list) -4):
                marks.append([])
        for idx,i in enumerate(range(4,len(grades_list))):
            marks[idx].append(int(grades_list[i]))
    for mark in marks:
        avgs.append(float(sum(mark)/(len(mark))))
    return avgs

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...