存储输入数字的哪种数据结构?

时间:2019-03-11 14:41:13

标签: python

哪种数据结构最适合计算输入数字的平均值? 我使用了数组,但感觉很笨拙。
有更标准的方法吗?

import os

def getGrades():
    g = input("How many tests?")
    numGrades = int(g)

    grades = []*numGrades

    for x in range(numGrades):
        t = int(input("Enter Grade #" + str(x+1) + ": "))
        grades.append(t)
    avgGrades(grades)

def avgGrades(a):
    total = 0
    count = 0
    for t in a:
        total = total + t
        count = count + 1
    avg = total / count
    print (f"average is: {avg}")


getGrades()

4 个答案:

答案 0 :(得分:2)

有一个statistics模块可以使用:

import statistics


def get_grades_avg():
    g = input("How many tests?")
    num_grades = int(g)
    grades = [] * num_grades
    for x in range(num_grades):
        grades.append(int(input("Enter Grade #" + str(x + 1) + ": ")))
    return statistics.mean(grades)


avg = get_grades_avg()
print('avg: {}'.format(avg))

答案 1 :(得分:0)

使用Python列表很好。也许尝试一些内置功能来获得平均成绩会更容易。

假设成绩是存储一些成绩的列表。

sum(grades) / len(grades)

答案 2 :(得分:0)

您可以使用以下内容:

def average_factory():
    count_numbers = 0
    sum_numbers = 0

    def wrapper(number):
        nonlocal count_numbers
        nonlocal sum_numbers
        sum_numbers += number
        count_numbers += 1
        return sum_numbers / count_numbers

    return wrapper


def get_number(message):
    str_number = input(message)

    try:
        return int(str_number)
    except (ValueError, TypeError):
        print('Invalid number, please try again')
        return get_number(message)


def get_average_of_all_tests():
    count_tests = get_number('How many tests? ')

    get_average = average_factory()
    average = 0

    for test_number in range(1, count_tests + 1):
        number = get_number('Enter Grade #{test_number}: '.format(test_number=test_number))
        average = get_average(number)
    return average

是的,对于一般工厂,此解决方案似乎有些复杂。但是我认为存储所有值只是为了计算平均值并不是一个好主意。只存储成绩和成绩总和更好。 如果您对解决方案有任何疑问,请随时问我。

答案 3 :(得分:-1)

numpy或scipy为此提供了良好的便利。

将您的号码存储在numpy.array([])中。 要获取您的平均值,numpy.mean(<yourarray>)

您的代码如下:

import numpy
import os

def getGrades():
    g = input("How many tests?")
    numGrades = int(g)

    grades = []*numGrades

    for x in range(numGrades):
        t = int(input("Enter Grade #" + str(x+1) + ": "))
        grades.append(t)
    yourArray = numpy.array(grades)
    return numpy.mean(yourArray)