从.text文件Python 3.4.1中查找中位数和模式

时间:2014-07-17 19:41:59

标签: python

我正在尝试从“numbers.txt”文件中的数字列表中确定中位数和模式。 我非常擅长python并且拥有ZERO编码经验。

这是我到目前为止计算平均值,总和,计数,最大值和分钟数,但我不知道从哪里开始。

number_file_name = 'numbers.txt'
number_sum = 0
number_count = 0
number_average = 0
number_maximum = 0
number_minimum = 0
number_range = 0

do_calculation = True
while(do_calculation):

    while (True):
        try:
            # Get the name of a file
            number_file_name = input('Enter a filename. Be sure to include .txt after the file name: ')
            random_number_count = 0

            print('')

            random_number_file = open(number_file_name, "r")
            print ('File Name: ', number_file_name, ':', sep='')

            print('')

            numbers = random_number_file.readlines()
            random_number_file.close
        except:
            print('An error occured trying to read', random_number_file)
        else:
            break

    try: 
        number_file = open(number_file_name, "r")

        is_first_number = True

        for number in number_file:
            number = int(number)  # convert the read string to an int

            if (is_first_number):
                number_maximum = number
                number_minimum = number
                is_first_number = False

            number_sum += number
            number_count += 1
            if (number > number_maximum):
                number_maximum = number
            if (number < number_minimum):
                number_minimum = number

        number_average = number_sum / number_count
        number_range = number_maximum - number_minimum

        index = 0
        listnumbers = 0
        while index < len(numbers):
            numbers[index] = int(numbers[index])
            index += 1


        number_file.close()
    except Exception as err:
        print ('An error occurred reading', number_file_name)
        print ('The error is', err)
    else:
        print ('Sum: ', number_sum)
        print ('Count:', number_count)
        print ('Average:', number_average)
        print ('Maximum:', number_maximum)
        print ('Minimum:', number_minimum)
        print ('Range:', number_range)
        print ('Median:', median)

    another_calculation = input("Do you want to enter in another file name? (y/n): ")
    if(another_calculation !="y"):
        do_calculation = False

2 个答案:

答案 0 :(得分:1)

如果您想查找数字的medianmode,则需要跟踪到目前为止遇到的实际数字。您可以创建一个list来保存所有数字,也可以创建一个dictionary映射数字来查看这些数字的频率。现在,让我们从这些数字创建(排序)列表:

with open("numbers.txt") as f:
    numbers = []
    for line in f:
        numbers.append(int(line))
    numbers.sort()

或更短:numbers = sorted(map(int, f))

现在,您可以使用各种builtin functions来计算计数,总和,最小值和最大值

count = len(numbers)
max_num = max(numbers)
min_num = min(numbers)
sum_of_nums = sum(numbers)

使用数字列表也可以非常快速地计算模式和中位数:

median = numbers[len(numbers)//2]
mode = max(numbers, key=lambda n: numbers.count(n))

答案 1 :(得分:0)

也许是有原因但你为什么要避免使用python库? Numpy和scipy应该拥有你正在寻找的所有任务。

查看numpy.genfromtxt()numpy.mean()scipy.stats.mode()