Python:如何读取数字的.txt文件以查找所述数字的中位数,而不使用中位数()?

问题描述 投票:0回答:1

我正在做一个作业,要求我们读入一个.txt数字文件,然后找出一种使用列表长度来确定数字列表的奇/偶长度的中间索引的方法,以计算中位数,而不使用中位数()调用。我不知道该怎么做,有什么帮助! (我对Python还是不满意)

debug = print

# assign name of file to be read
file = "numbers_even.txt"

# open file to be read
def get_median(med):
    with open(file, mode='r') as my_file:
    # assign middle index values for list    
        m2 = len(file) // 2
        debug("index2", m2)

        m1 = m2 -1

        value1 = file[m1]
        debug(m1, value1)

        value2 = file[m2]

        middle = (value1 + value2) / 2
        debug("val1:", value1, "val2:", value2, "mid", middle)
    # end with
# end function

get_median(file)
python list function readfile median
1个回答
0
投票

我建议将所有数字都放入列表中。然后,您可以对列表进行排序并选择中间索引。

© www.soinside.com 2019 - 2024. All rights reserved.