Python帮助|从.txt文件的列表中创建平均值?

Python帮助|从.txt文件的列表中创建平均值?,python,Python,以下是典型的打印输出: classs = input("Class [1, 2 or 3] - ") if clas data = f.readlines() for le: print(line) found = True if found == False: print("False") 我需要能够通过使用10,4,6创建一个平均值,因为我需要知道一种

以下是典型的打印输出:

classs = input("Class [1, 2 or 3] -  ")

if clas
        data = f.readlines()
        for le:
                print(line)
                found = True
        if found == False:
            print("False")
我需要能够通过使用
10,4,6
创建一个平均值,因为我需要知道一种方法来隔离其余部分,并允许数字继续,以便创建平均分数

希望有人能理解这一点,并能提供帮助

提前感谢

如果每行的格式相同,可以使用
string.split
并转换为
int

John = 10
John = 6
John = 4
然后浏览数字列表,得到平均值,如:

classs = input("Class [1, 2 or 3] -  ")
l = []

if classs =='1':
    name = input("What is your name? -  ")

    datafile = '1.txt'
    found = False

    with open(datafile, 'r') as f:
        data = f.readlines()
        for line in data:
            if name in line:
                print(line)
                l.append(int(line.split()[2]))
                found = True
        if found == False:
            print("False")

一种方法是从您的列表中提取每个玩家的最后3个数字(我假设您只需要3个,如果不需要,此代码可以修改更多)

Class=输入(“类:”)
数据列表=[]
file=open('class'+str(class)+'.txt',“r”)
对于文件中的行:
计数=0
记录=行
studentList=record.split(“:”)
分数=学生列表[1]。带('\n')
studentList=[studentList[0],分数]
如果len(数据列表)==0:
dataList.append(studentList)
其他:
当计数
这将为您提供一个二维数组。其中每个较小的数组将在索引0处包含人名,在索引1、2和3处包含三个数字。现在你有了这些,你可以简单地计算出平均值

Class = input("Class: ")
dataList = []
file = open('class ' + str(Class) + '.txt', "r")
for line in file:
    count = 0 
    record = line
    studentList = record.split(': ')
    score = studentList[1].strip('\n')
    studentList = [studentList[0], score]
    if len(dataList) == 0:
        dataList.append(studentList)
    else:
        while count < len(dataList):
            if studentList[0] == dataList[count][0]:
                if len(dataList[count]) == 4:
                    dataList[count][3] = dataList[count][2]
                    dataList[count][2] = dataList[count][1]
                    dataList[count][1] = score
                    break
                dataList[count].append(score)
                break
            elif count == len(dataList) - 1:
                dataList.append(studentList)
                break
            count = count + 1
AverageScore=[]
#这是保存学生记录(姓名和最高分数)的数组
#列表中
计数=0
当计数

冗长而低效,但这是我对python的一点了解所能做到的最好的:)

如果这是
1.txt的内容:

AverageScore = []
# this is the array where the student' record (name and highest score) is saved
# in a list
count = 0
while count < len(dataList):
    entry = []
# this is whre each student name and score will be temporarily held
    entry.append(dataList[count][0])
# this makes it so the array 'entry' contains the name of every student
    Sum = 0
    frequency = len(dataList[count])
    incount = 1
    while incount < frequency:
        Sum = Sum + int(dataList[count][incount])
        incount = incount + 1 
    average = Sum / (frequency-1)
    entry.append(average)
    AverageScore.append(entry)
# this appends the name and average score of the student to the larger array
# 'AverageScore'
    count= count + 1
# the count is increased so the process is repeated for the next student
AverageSorted = sorted(AverageScore,key=lambda l:l[1], reverse=True)
# http://stackoverflow.com/questions/18563680/sorting-2d-list-python
# this is code i obtained through someone else's post which arranges the array in descending
# order of scores
count2 = 0
while count2 < len(AverageSorted):
    print(AverageSorted[count2][0], ':', AverageSorted[count2][1])
    count2 = count2 + 1
# this formats the array so it prints the elements in a list of each student's
# name and score
将您的“with”语句替换为:

John = 1
Joe = 3
John = 7
Joe = 9
Bob = 3
Joe = 8
John = 2
Bob = 9
Roger = 13

很抱歉造成麻烦,但是使用它们3个结果我将如何找到平均值?输出结果的格式把我弄糊涂了。你能不能?给我任何见解,我真的卡住了!通过调用列表
列表
,您接管了任务并使代码更加混乱。一个问题,当程序输出平均值时,它会在每次结果后输出它,例如-John=1,您的平均值为1.0 John=3你的平均值是2.0我的问题是如何让它在输出最后一个分数后输出平均值。而不是在每次连续得分之后?你把平均数计算器放在哪里了?把它放在“with open”块之后。如何提取列表中的数字?你能把它放进一个变量中,然后你就可以很容易地得到一个平均值吗?我该如何在其他两个类中重复这个?(2.txt)和(3.txt)总共有3个类。您可以将类号格式化为第三行的文件名:
,将open(“%s.txt”%class,“r”)作为out:
。对不起,我不明白,您可以在代码中加密它吗。对于2+3类,我将您要求的代码添加到我的原始响应中。
John = 1
Joe = 3
John = 7
Joe = 9
Bob = 3
Joe = 8
John = 2
Bob = 9
Roger = 13
name = "John"
_class = 1

with open("%s.txt" % _class, "r") as out:
    lines = out.readlines()

    scores = []

    for line in lines:
        if name in line:
            # "strip" without arguments strips out all beginning
            # and trailing white-space (i.e. " ", "\n", "\r").
            line = line.strip()

            score = int(line.split(" = ")[1])

            scores.append(score)

    # If there isn't any scores in this list, then there was no user
    # data.
    if scores:
        # Use python built-in sum to sum the list of scores and
        # divide the result by the number of scores gives you the average.
        average = sum(scores) / len(scores)

        print "%s's average score is %.1f out of %d game(s)." % (
            name, average, len(scores))

    else:
        print "User %s not found." % name