【问题标题】:Create averages from a list from .txt file?Python 帮助 |从 .txt 文件的列表中创建平均值?
【发布时间】:2016-01-21 02:20:05
【问题描述】:
classs = input("Class [1, 2 or 3] -  ")

if clas
        data = f.readlines()
        for le:
                print(line)
                found = True
        if found == False:
            print("False")

这是一个典型的打印输出:

John = 10
John = 6
John = 4

我需要能够仅通过使用 10, 4, 6 来创建平均值,因为我需要知道一种方法来隔离其余部分并允许数字继续以创建平均分数。

希望有人明白这一点并能够提供帮助!

提前致谢!

【问题讨论】:

    标签: python


    【解决方案1】:

    如果每个格式都相同,可以使用string.split并强制转换为int

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

    然后遍历数字列表并获得平均值,例如:

    total = 0
    num = 0
    for x in l:
        total = total + x
        num = num + 1
    print(total/num)
    

    【讨论】:

    • 抱歉打扰了,但是使用它们 3 结果我将如何找到平均值?输出结果的格式让我很困惑。
    • 可以吗?给我任何见解,我真的卡住了!
    • 通过调用您的列表list,您将接管builtin function list() 并使您的代码更加混乱。
    • 一个问题,当程序输出平均值时,它会在每个结果之后输出它,例如 - John = 1 你的平均值是 1.0 John = 3 你的平均值是 2.0 我的问题是我如何让它输出输出最后一个分数后的平均值。而不是在每个连续得分之后?
    • 你把平均计算器放在哪里了?将它放在“with open”块之后。
    【解决方案2】:

    一种方法是从您的列表中提取每个玩家的最后 3 个数字(我假设您只需要 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
    

    这会给你一个二维数组。每个较小的数组都将在索引 0 处包含人员姓名,并且在索引 1,2 和 3 处包含三个数字。现在你有了这些,你可以简单地计算出平均值。

    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
    

    冗长且效率低下,但它是我能用我对 python 的小知识做的最好的:)

    【讨论】:

    • 如何提取列表中的数字?您能否将其放入一个变量中,然后您可以轻松地进行平均?
    【解决方案3】:

    如果这是1.txt的内容:

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

    用这个替换你的“with”语句:

    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
    

    【讨论】:

    • 我将如何为其他 2 个课程重复此操作? (2.txt) 和 (3.txt) 总共有 3 个类。
    • 您可以将班级编号格式化为文件名,如下所示:with open("%s.txt" % class, "r") as out:
    • 对不起,我不明白,你能不能在代码中加密它。所以对于 2 + 3 类。
    • 我将您请求的代码添加到我的原始回复中。
    猜你喜欢
    • 2014-07-15
    • 1970-01-01
    • 2012-08-15
    • 2014-04-20
    • 1970-01-01
    • 1970-01-01
    • 2017-01-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多