2016-11-17 101 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”或其他一些随机废话(如其他答案中列出的那些)。 ;) –