如何在Python 3.5.2中创建文本文件的平均值?

时间:2016-11-17 04:26:15

标签: python

我现在已经挣扎了两天,我似乎无法找到任何帮助。我需要在文件中搜索学生ID(1001是我正在使用的测试ID),然后在每次出现的学生ID下面的每一行中添加数字,以获得平均值。

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

4 个答案:

答案 0 :(得分: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

一些有用的参考资料:

答案 1 :(得分: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]

在这一点上,你可以总结,平均,最大或最小你想要的任何东西。

答案 2 :(得分:0)

请不要将此代码用于您的作业(使用@ Aditya&#39的方法);在使用花式库之前,您需要学习基础知识。但是,我刚刚了解了/^(REGEXP-FOR-7-CHARS|REGEXP-FOR-13-CHARS)$/ ^ ALTERNATION (PIPE/OR) ,我想使用它。观看/^(\d{7}|\d{13})$/ ,了解collections.defaultdict上的精彩演示。

defaultdict

答案 3 :(得分:0)

更新的答案:

好的,所以我想我现在理解你的问题了......同样的事情,除了我建议使用列表,只要文件保持相同的格式(SID,分数等等),这个应该工作,并且需要对Python的最小理解(即没有像 glob 那样奇怪的库):

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

这将返回一个整数,或者与您的文件一起打印:

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. 

无论这回答了你的问题,我的学习基础知识的提示是理解文件类型以及它们可以做什么。 在您的情况下,您将主要需要关注字符串(文本)和整数(整数)。使用Pythons IDLE,声明一个变量,然后输入名称和一个点,并使用tab滚动浏览每个可用的函数。 例如:

Occurrences: 4

从列表中选择一个表格后,输入一个左括号"(",它将简要说明它的作用。

希望有所帮助,并且对于冗长的回复感到抱歉(我试图解释并指出(提示),因为你说你是菜鸟)