def median(numbers):
numbers.sort()
if len(numbers) % 2:
# if the list has an odd number of elements,
# the median is the middle element
middle_index = int(len(numbers)/2)
return numbers[middle_index]
else:
# if the list has an even number of elements,
# the median is the average of the middle two elements
right_of_middle = len(numbers)//2
left_of_middle = right_of_middle - 1
return (numbers[right_of_middle] + numbers[left_of_middle])/2
结果示例:
>>> x=[5,10,15,20]
>>> median(x)
12.5
>>> x=[17,4,6,12]
>>> median(x)
9.0
>>> x=[13,6,8,14]
>>> median(x)
10.5
我已经运行了这个功能,它工作正常。一开始很难理解结果,但最终我明白了!
但是,我不明白为什么只有第一个结果像预期的那样。我的意思是结果是列表中间两个数字的平均值。
我希望你明白我是在自学,有时这并不容易。