【问题标题】:How to print out who has the lowest and highest scores in a test?如何打印出谁在考试中得分最低和最高?
【发布时间】:2018-02-21 04:19:18
【问题描述】:

代码

import re
from functools import reduce

def median(lst):
    n = len(lst)
    if n < 1:
        return None
    if n % 2 == 1:
            return sorted(lst)[n//2]
    else:
            return sum(sorted(lst)[n//2-1:n//2+1])/2.0

def main():
    file = open("grades.txt","r")
    i = file.readlines()
    num=[]
    for element in i:
        num.extend((re.findall('\d+',element)))
    results = list(map(int, num))
    print(results)
    print (reduce(lambda x, y: x + y, results) / len(results))
    print(median(results))

main()

文本文件:

盖尔,宇治房,95

贝拉,露娜,65

鲍勃,琼斯,0

亚历克斯,芬克,10

内森,波诺,0

鲍勃,波诺,0

伊迪丝,波诺,0

苏西,阙,84

阿诺德,乔治,80

琳达,贝丝,100

【问题讨论】:

    标签: python file for-loop if-statement


    【解决方案1】:

    Python 知识的一个重要部分是知道已经存在的内容然后使用它。有用于查找最小值 (min) 和最大值 (max) 值的内置函数。在“统计”模块中还内置了用于查找平均值和中值的统计函数。你应该努力使用它们。

    不过,要查找多次出现的最小值或最大值,您可能需要再次遍历数据。你的代码可以写成:

    import re
    from statistics import median, mean
    
    # Read in results into a dict, to allow further manipulation:
    persons = {}
    with open('grades.txt', 'r') as f:
        for line in f:
            m = re.match('(.*),(.*),(.*)', line)
            if m:
                person = '{} {}'.format(m[1], m[2])
                grade = int(m[3])
                persons[person] = grade
    
    # Find min and max grade value
    # Only look for the value since the dict needs to be iterated to find
    # multiple occurances anyway.
    min_grade = min(persons.values())
    max_grade = max(persons.values())
    
    # Loop dict to find all persons with min/max grades
    lowest = []
    highest = []
    for person, grade in persons.items():
        if grade == min_grade:
            lowest.append(person)
        if grade == max_grade:
            highest.append(person)
    
    # Gather and print statistics
    print('Stats:')
    print('Min grade {}: {} ({})'.format(
            min_grade, ', '.join(lowest), len(lowest)))
    print('Max grade {}: {} ({})'.format(
            max_grade, ', '.join(highest), len(highest)))
    print('Median: {}'.format(median(persons.values())))
    print('Mean: {}'.format(mean(persons.values())))
    
    # Print all students and their grades, somewhat formatted
    print('\nGrade list:')
    for person, grade in persons.items():
        print('{:14} {:3}'.format(person, grade))
    

    这与您的代码完全不同。不过,它确实有许多不错的 Python 构造,您应该尝试学习和使用它们,例如 with 构造和逐行读取文件。它还使用了非常好的dict 数据类型。此外,它避免了reduce,因为有很多人认为这会使代码更难阅读(尽管我个人喜欢它)。

    【讨论】:

      猜你喜欢
      • 2017-02-08
      • 2021-05-08
      • 1970-01-01
      • 2020-05-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-04
      • 1970-01-01
      相关资源
      最近更新 更多