【问题标题】:Return the average mark for all student in that Section返回该部分所有学生的平均分
【发布时间】:2012-10-28 06:12:20
【问题描述】:

我知道它已经被问过了,但答案超级不清楚

第一个要求是打开一个文件(遗憾的是我不知道该怎么做)
第二个要求是执行以下操作的一段代码:

每一行代表一个学生,由一个学号、一个姓名、一个部门代码和一个期中成绩组成,全部用空格分隔

所以我不认为我可以定位该元素,因为它被空格分隔?

这是文件的摘录,显示了行结构

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

我得到了以下提示:

  • 请注意,每个学生的姓名数量会有所不同。
  • 使用rstrip() 去除行尾多余的空格。

我不明白第二个提示。

这是我目前所拥有的:

counter = 0  
elements = -1  

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

我知道这与readlines() 和定位部分代码有关。

【问题讨论】:

  • 你想问什么问题?
  • 在这种情况下使用 readlines。而且我确定我不能继续我已经写的方式了。
  • 您是否尝试 Google python rstrip 以更好地理解第二个提示?
  • 你试过谷歌how to open a file in python吗?

标签: python whitespace space average


【解决方案1】:

Open and writing to files strip method

这样的?

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']))

【讨论】:

  • 我不认为我们通过提供准备好的代码来帮助学生完成家庭作业和学习。
  • 你会建议删除我的答案吗?
  • 我认为这是有帮助的。对于计算机科学,有时我认为看到成品后更容易理解。如果你愿意就删除
  • setdefault() 或 DefaultDict 将摆脱你内心的if 检查。
  • 当然我知道,但看起来这个级别真的是初学者
【解决方案2】:

或多或少:

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

【讨论】:

  • 认为您忘记将字符串转换为浮点数 - 否则您会将字符串表示合并为一个大字符串
【解决方案3】:
marks = [float(line.strip().split()[-1]) for line in open('path/to/input/file')]
average = sum(marks)/len(marks)

希望对你有帮助

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多