从python中的输入数字列表中求平均值

时间:2016-02-16 04:27:18

标签: python math

我是编码的新手,这是python的介绍编码类。 我必须写一个姐妹程序,它使用循环来读取和处理a.txt文档以获得随机整数列表。  程序必须在由空格分隔的一行上输出文件中的所有整数。 程序还必须输出偶数整数的平均值和奇数整数的平均值。两个平均值必须精确到小数点后四位。

粗体文字是我需要帮助的..这是我到目前为止的...我知道如何设置小数,但我似乎无法弄清楚如何写平均值的偶数和奇数。

def main():
    total = 0

    numfile = open('mynumbers.txt','r')

    line = numfile.readline()

    while line != '':
        numb = int(line)
        print(numb,end=' ')
        line = numfile.readline()
        #calculation for average of odds
        #calculation for average of evens


    numfile.close()
    print('\n' + 'Average of the even numbers:',)
    print('Average of the odd numbers:',)
main()

代码输出:

98 62 60 15 74 68 51 15 

Average of the even numbers: 

Average of the odd numbers:

我的班级示例输出:

40 90 89 57 90 19 88 78 

Average of the even numbers: 77.2000

Average of the odd numbers: 55.0000

2 个答案:

答案 0 :(得分:0)

这应该有效(请参阅代码注释以获得解释):

def main():
    total = 0
    evens = []
    odds = []
    numfile = open('mynumbers.txt','r')

    line = numfile.readline()

    while line != '':
        numb = int(line)
        print(numb,end=' ')
        line = numfile.readline()
        # here you're checking each number and adding it to the apt list
        if numb%2 == 0:
           evens.append(numb)
        elif numb%2 == 1:
           odds.append(numb)

    numfile.close()
    # here you're getting the sum and rounding it
    e_avg = round(sum(evens)/len(evens),4)
    o_avg = round(sum(odds)/len(odds),4)

    print('\n' + 'Average of the even numbers: '+e_avg)
    print('Average of the odd numbers: '+o_avg)
main()

答案 1 :(得分:0)

嗯,模(%)字符可以帮助你做平均值和赔率。首先,让我们首先将所有数字放在一个列表中。

def main():
    total = 0

    numfile = open('mynumbers.txt','r')

    line = numfile.readline()

    nums = []

    while line != '':
        numb = int(line)
        print(numb,end=' ')
        nums.append(numb)
        line = numfile.readline()
        #calculation for average of odds
        #calculation for average of evens


    numfile.close()
    print('\n' + 'Average of the even numbers:',)
    print('Average of the odd numbers:',)
main()

现在最后我们可以计算平均值。这将为您提供平均值和赔率。它的工作原理是将所有的平均值或赔率相加,然后除以均数或赔率。

伊文思:

average = sum([i for i in nums if i%2==0])/len([i for i in nums if i%2==0])

和赔率的平均值:

average_odds = sum([i for i in nums if i%2==1])/len([i for i in nums if i%2==1])

并将它们打印到4位小数:

print("Even Average: {0:.5}".format(average))
print("Odd Average: {0:.5}".format(average_odds))

现在,由于这是一项家庭作业(我认为),您应该将其实施到您的整个计划中。