2012-11-08 45 views
0

我知道有人已經問,但答案超級不清楚返回的平均得分爲所有的學生該科

的第一個要求是要打開一個文件(可惜我不知道該怎麼做)
第二個要求是一個代碼部分,其執行以下操作:

每條線代表單個學生和由學生號碼,姓名,一個區段碼和中期級的,全部由空白

分離

所以我不這麼認爲由於它被空白分隔,我可以定位該元素嗎?

這裏是文件的摘錄,表示線路結構

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()和靶向的部分代碼。

+0

什麼是你想要的問題要問? –

+0

http://www.cdf.toronto.edu/~csc108h/fall/exercises/e3/grade_file.txt – AlwaysNeedsHelp

+0

在這種情況下使用readlines。我確信我不能繼續我已經寫過的方式。 – AlwaysNeedsHelp

回答

0

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

我不'我認爲我們正在幫助學生完成他們的作業,並通過提供準備好的代碼來幫助學生。 – mjv

+0

你會建議刪除我的答案嗎? –

+0

我認爲這是幫助。對於計算機科學有時候我認爲它更容易理解成品。刪除,如果你會 – AlwaysNeedsHelp

0

或多或少:

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 
+0

認爲您忘記將字符串轉換爲浮點數 - 否則將字符串表示法合併爲一個大字符串 –

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

希望這有助於