【问题标题】:How to find the median?如何找到中位数?
【发布时间】:2013-08-08 16:23:37
【问题描述】:

我正在尝试创建一个可以获取任意数量的输入并找到中位数的函数。我觉得我做错了,我无法获得这个功能。
我需要做什么?

  1. 我列出了我的清单
  2. 我要求用户输入
  3. 我用 numpy 排序
  4. 我打印了中位数

代码:

import numpy

numbers = [1,2,3]                
1 = input("Please type your first number")            
2 = input("please type your second number")       
3 = input("please type your third number")       
median = numpy.median(numbers)            
print(median) 

我想要完成的事情:

您希望找到哪些数字的中位数? 1,2,3,4,5,6,7
中位数为:4

【问题讨论】:

  • 您不能分配给11 是一个数字;你不能把它变成2 什么的。
  • 我刚开始编程,我不知道。我将如何分配它?
  • 分配给变量或列表元素,或将输入附加到列表中。
  • 你安装了 NumPy 吗?
  • 就 DL 吧!它现在可以工作了。

标签: python python-3.x numpy median


【解决方案1】:

您应该将数字存储在一个列表中,并使用循环向其中添加数字。

import numpy

size = int(input("Enter number of numbers you would like to enter"))
numbers = []
for i in range(size):
    numbers.append(int(input("Please type in number %d" % i)))

median = numpy.median(numbers)  

print(median) 

您的方法失败了,因为您尝试使用数字作为变量名,这是无效的。

【讨论】:

  • 不确定这个答案有什么问题,所以我想要一些反馈!
  • 作为一个新手程序员,我不知道我必须下载 NumPY,在这样做之后我最终使用了它。这很有帮助!
【解决方案2】:

您不能将值分配给 1、2 或 3。此外,您需要将字符串从 input 转换为 ints。尝试一些简单的更改。

import numpy                
input1 = input("Please type your first number")            
input2 = input("Please type your second number")       
input3 = input("Please type your third number")
numbers = map(int, [input1, input2, input3])
median = numpy.median(numbers)            
print(median) 

【讨论】:

  • 我发现我的代码具有误导性,这有助于我了解我应该为功能做些什么。虽然我是为了 @jh314 发布的内容。
猜你喜欢
  • 2012-05-15
  • 1970-01-01
  • 1970-01-01
  • 2014-12-31
  • 2021-11-11
  • 2021-04-28
  • 2014-01-01
  • 2021-11-10
  • 1970-01-01
相关资源
最近更新 更多