2016-11-17 64 views
0

我一直在爲此掙扎兩天,似乎無法找到任何幫助。我需要在文件中搜索學生ID(1001是我使用的測試ID),然後將每個出現在學生ID下方的每行中的數字加在一起,以獲得平均值。如何從Python 3.5.2中的文本文件創建平均值?

filename = input("Enter file name: \n" 
       "Example: Grade Data.txt \n") 
myFile = open(filename, "r")  
selectSID = input("Enter SID: \n") 
gradesNum = myFile.read().count(selectSID) 
grades = myFile.read() 
gradetotal = sum() 
average = (gradetotal/gradesNum) 
print(average) 

正在打開看起來像這樣的文本文件:

1001 
95 
1002 
99 
1001 
96 
1002 
0 
1001 
84 
1002 
25 
1001 
65 
1002 
19 
+3

你沒有給一個參數到'sum()',它得到的總和是多少? – Barmar

+1

如果你的導師沒有教它,也許它在教科書中?我無法相信他給沒有教過的東西做作業。特別是 – Barmar

回答

4

這看起來像功課,所以我不想爲你寫的代碼,但這裏是一個僞代碼(有多種方式來實現你想要什麼,這只是一個簡單的入門級代碼):

Open file to read 
get two lines from the file 
    is the line1 interesting to me? 
     yes -> store value from line2 in an array 
     no -> ignore line2 
close file 

get average 

的一些有用參考:

+0

,請查看[statistics.mean](https://docs.python.org/3/library/statistics.html#statistics.mean)。 – Ben

0
from collections import defaultdict 
# with open('filename') as f: 
#  file = [for i in f] 
# in this case, it's the list below 
file = [1001,95,1002,99,1001,96,1002,0,1001,84,1002,25,1001,65,1002,19] 
infos = defaultdict(list) 
sids = file[::2] # select sid info 
grades = file[1::2] # select grade info 

for sid,grade in zip(sids,grades): 
    infos[sid].append(grade) 

print(infos[1001]) 
print(infos[1002]) 

出來:

[95, 96, 84, 65] 
[99, 0, 25, 19] 
在這一點上

,你可以總結,平均,最大或任何你想分鐘。

0

請不要使用此代碼作家庭作業(使用@ Aditya的方法);你需要在使用花哨的庫之前學習基礎知識。不過,我剛剛瞭解到collections.defaultdict,我想用它。在defaultdict上觀看this video的精彩演示。

import collections 
import statistics 

# This little guy will hold all of our grades 
# https://youtu.be/lyDLAutA88s is a great video using it 
grades = collections.defaultdict(list) 

def get_next_num(file): 
    """get the next line of a file, 
    remove any whitespace surrounding it, 
    and turn it into an integer""" 
    return int(next(file).strip()) 

with open('tmp.txt') as myfile: 
    while True: 
     try: 
      # seriously, watch the video 
      grades[get_next_num(myfile)].append(get_next_num(myfile)) 
     except StopIteration: # end of file 
      break 
student_id = int(input('Enter student ID. Choices: {} : '.format(list(grades.keys())))) 
print(statistics.mean(grades[student_id])) 
0

更新答:

好了,所以我想我明白你的問題......現在同樣的事情,但我建議使用一個列表,只要文件保持相同的格式(SID ,分數,等...),這應該工作,並需要Python的最小理解(即沒有怪異的庫,例如水珠):

filename = input("Enter file name: \n" 
      "Example: Grade Data.txt \n") 
myFile = open(filename, "r")  
selectSID = input("Enter SID: \n") 
raw = myFile.read() ## Raw contents of file. 
val = raw.count(selectSID) ## Returns number of occurences 
print("Occurrences: ", val) ## Or do something else... 

lines = raw.split("\n") ## Create a list containing each new line 
scores = [] ## A list that will contain all your scores 
while selectSID in lines: 
    val = lines.index(selectSID) ## Returns where it is in the list, 
    score = lines[ val+1 ] ## Gets the item at that position (index) Because the score is one line after the SID 
    scores.append(int(score)) ## Adds the score to the list. --Suggest you look into how to safely capturing "int"s (try, except, etc) so the program doesn't crash if the score isn't a number (Advance) 
    lines.remove(selectSID) ## automatically removes first occurrence of the SID (cause that's the one we just used) 
avg = sum(scores)/len(scores) ## sum() function is self explanatory (takes a list or tuple [a sequence] and adds all values (must be all numbers), THEN len() is just length. 

這將返回一個整數,或與您的文件,將打印:

Occurrences: 4 


而不管是否回答了你的問題,我的學習基礎知識技巧是理解的文件類型和他們能做什麼。 就你而言,你將主要需要關注字符串(文本)和整數(整數)。使用Pythons IDLE,聲明一個變量,並輸入名稱和點,並使用Tab滾動瀏覽可用的每個函數。 例子:

>>> myString = "Hello World" 
>>> myString.[TAB] #--> [Context Menu Here] 

一旦選擇了一種形式的列表,請輸入一個左括號「(」,這將會給他們做一簡要說明。



希望幫助,併爲冗長的答覆對不起(我試圖解釋和指點(TIPS),因爲你說你是一個小白)

+0

你在哪裏計算等級的平均值? – Barmar

+0

@Barmar對不起,我只是想出了其他數字。答案已更新。非常基本。冗長,但這是我建議你做你的程序,直到你理解更多的核心概念,然後解決功能,模塊/庫如「導入glob」或其他一些隨機廢話(如其他答案中列出的那些)。 ;) –