如何打印出测试中得分最低和最高的人?

时间:2018-02-21 04:19:19

标签: python file for-loop if-statement

代码

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

文字档案

盖尔,Ujifusa,95

贝拉,露娜,65

鲍勃,琼斯,0

亚历克斯,芬克,10

森,波诺,0

鲍勃,波诺,0

伊迪丝,波诺,0

苏西,阙,84

阿诺,乔治,80

琳达,贝斯,100

1 个答案:

答案 0 :(得分:0)

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

要查找最小值或最大值的多次出现,您可能需要第二次循环访问数据。您的代码可以写成:

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,因为有许多人认为这会使代码更难阅读(即使我个人喜欢它)。