从文件列表中将行更改为列

2024-10-05 13:18:06 发布

您现在位置:Python中文网/ 问答频道 /正文

有人知道我怎么把作业从这个文件中穿插出来吗?你知道吗

Here is the file, grades.csv and the format.

       Last Name,First Name,Student No.,uTORid,A1,A2,A3,A4
       Smith,Joe,9911991199,smithjoe9,99,88,77,66
       Ash,Wood,9912334456,ashwood,11,22,33,44
       Full,Kare,9913243567,fullkare,78,58,68,88

我想得到这样的结果,然后加上所有赋值的总值,然后除以每个赋值的赋值数,得到平均值

       [99, 11, 78]
       [88, 22, 58]
       [77, 33, 68]
       [66, 44, 88]

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.
'''

      new_list = []
for line in open_file:
    grades_list = line.split(',')
    marks1 = grades_list[4:5]
    marks2 = grades_list[6:7]

    for item in range(min(marks1, marks2)):
        added_marks = marks1[item] + marks2[item]

这是我到目前为止,不太清楚如何继续


Tags: ofthenameinforopenitemlist
2条回答

昨天我问了一个类似的问题。你知道吗

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

在这种情况下,枚举和迭代是您的朋友。通过内置函数,求平均值很简单

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=[[],[],[],[]]

    for line in open_file:
        grades_list = line.strip().split(',')
        for idx,i in enumerate(range(4,8)):
            marks[idx].append(int(grades_list[i]))    
    avgs = [] 

    for mark in marks:
        avgs.append(float(sum(mark)/(len(mark))))
    return(avgs)

相关问题 更多 >

    热门问题