在这个例子中如何不硬编码功能

时间:2017-11-05 04:11:16

标签: python python-3.x

以下链接包含2个csv文件,该函数应通过grades_1e_2a grades_2e_4a

但是我的功能只能传递第二个链接文件,因为它被硬编码到range(4,8)。 输出:[91.5, 73.5, 81.5, 91.5] 输入文件将从第4个元素开始,但可能不一定以第8个元素结束。

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

如何解决此问题,以便我的代码能够读取这两个文件或任何文件? 我已经打开了文件,并在同一文件的前一个函数中使用file.readline()遍历第一行。 感谢大家的帮助。

更新进度:https://gyazo.com/064dd0d695e3a3e1b4259a25d1b0b1a0

3 个答案:

答案 0 :(得分:1)

试试这样:

def class_avg(open_file, start = 4, end = 8):
...
...
    for idx,i in enumerate(range(start, end)):

答案 1 :(得分:1)

由于两组数据的起始位置相同,因此以下方法有效 for idx,i in enumerate(range(4,len(grades_list))):

这应该满足我到目前为止所知的所有要求

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

答案 2 :(得分:-2)

尝试使用:

     for idx,i in enumerate(range(4,len(grades_list))):
         marks[idx].append(int(grades_list[i]))

考虑到您知道有多少作业并相应地初始化了标记列表。