[英]Python: How do I read a .txt file of numbers to find the median of said numbers without using median() call?
I am working on an assignment that requires us to read in a.txt file of numbers, then figure out a way to use the length of the list to determine the middle index of both odd/even lengths of number lists to calculate the median without using the median() call.我正在做一项任务,要求我们读取 a.txt 数字文件,然后找出一种方法来使用列表的长度来确定数字列表的奇数/偶数长度的中间索引来计算中位数而不使用 median() 调用。 I do not understand how I would go about this, anything helps!
我不明白我怎么会 go 关于这个,有什么帮助! (I am also still faily new to Python)
(我对 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)
I would recommend pulling all the numbers into a list.我建议将所有数字拉到一个列表中。 Then you can sort the list and choose the middle index.
然后您可以对列表进行排序并选择中间索引。
Assuming your text file (numbers_even.txt) looks something like this:假设您的文本文件 (numbers_even.txt) 看起来像这样:
1
2
3
4
5
6
7
8
9
10
11
You can do this:你可以这样做:
with open('numbers_even.txt','r') as f:
median = f.readlines()
if len(median) % 2 == 0:
print(median[int(len(median)/2-1)])
else:
print((int(median[int(len(median)//2)])+int(median[int(len(median)//2-12)]))/2)
Output: Output:
5.5
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.