简体   繁体   English

返回该部分中所有学生的平均分数

[英]Return the average mark for all student in that Section

I know it was asked already but the answers the super unclear 我知道已经有人问过,但答案还不清楚

The first requirement is to open a file (sadly I have no idea how to do that) 第一个要求是打开一个文件(可悲的是我不知道该怎么做)
The second requirement is a section of code that does the following: 第二个要求是执行以下操作的一段代码:

Each line represents a single student and consists of a student number, a name, a section code and a midterm grade, all separated by whitespace 每行代表一个学生,由一个学生编号,一个姓名,一个区号和一个期中成绩组成,全部用空格隔开

So I don't think i can target that element due to it being separate by whitespace? 所以我不认为我可以定位该元素,因为它被空格分隔了吗?

Here is an excerpt of the file, showing line structure 这是文件的摘录,显示了行结构

987654322  Xu  Carolyn  L0101   19.5
233432555    Jones  Billy Andrew      L5101   16.0
555432345    Patel  Amrit                 L0101   13.5
888332441    Fletcher Bobby L0201   18
777998713   Van Ryan  Sarah Jane         L5101   20 
877633234    Zhang  Peter             L0102   9.5
543444555    Martin  Joseph           L0101   15    
876543222    Abdolhosseini  Mohammad Mazen  L0102 18.5

I was provided the following hints: 提供了以下提示:

  • Notice that the number of names per student varies. 请注意,每个学生的名字数量有所不同。
  • Use rstrip() to get rid of extraneous whitespace at the end of the lines. 使用rstrip()消除行尾的多余空格。

I don't understand the second hint. 我不明白第二个提示。

This is what I have so far: 这是我到目前为止的内容:

counter = 0  
elements = -1  

for sets in the_file  
    elements = elements + 1  
    if elements = 3  

I know it has something to do with readlines() and the targeting the section code. 我知道这与readlines()和定位部分代码有关。

marks = [float(line.strip().split()[-1]) for line in open('path/to/input/file')]
average = sum(marks)/len(marks)

Hope this helps 希望这可以帮助

Open and writing to files strip method 打开并写入文件 剥离方法

Something like this? 像这样吗

data = {}
with open(filename) as f:#open a file

    for line in f.readlines():#proceed through file lines

        #next row is to split data using spaces and them skip empty using strip
        stData = [x.strip() for x in line.split() if x.strip()]

        #assign to variables
        studentN, studentName, sectionCode, midtermGrade = stData
        if sectionCode not in data:
            data[sectionCode] = []

        #building dict, key is a section code, value is a tuple with student info
        data[sectionCode].append([studentN, studentName, float(midtermGrade)]

#make calculations
for k,v in data.iteritems():#iteritems returns you (key, value) pair on each iteration
    print 'Section:' + k + ' Grade:' + str(sum(x[2] for x in v['grade']))

more or less: 或多或少:

infile = open('grade_file.txt', 'r')
score = 0
n = 0
for line in infile.readlines():
    score += float(line.rstrip().split()[-1])
    n += 1

avg = score / n

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM