简体   繁体   English

如何找到中位数?

[英]How to find the median?

I am trying to create a function that can get any number of inputs and find the median. 我正在尝试创建一个可以获取任意数量的输入并找到中位数的函数。 I feel like I am going about this all wrong, I cannot get this functional. 我觉得我要解决所有这些错误,我无法获得此功能。
What do I need to do? 我需要做什么?

  1. I made my list 我列出了清单
  2. I asked user for inputs 我要求用户输入
  3. I sorted with numpy 我用numpy排序
  4. I printed median 我印了中位数

Code: 码:

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) 

What I am trying to accomplish: 我要完成的工作:

What numbers would you like to find the median for? 您想找到什么数字的中位数? 1,2,3,4,5,6,7 1,2,3,4,5,6,7
The median is: 4 中位数是:4

You should store the numbers in a list, and use a loop to add numbers to it. 您应该将数字存储在列表中,并使用循环将数字添加到列表中。

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) 

Your approach fails because you try to use numbers as variable names, which is not valid. 您的方法失败,因为您尝试将数字用作变量名,这是无效的。

You cannot assign values to 1, 2, or 3. Additionally, you need to convert the strings from input to int s. 您不能将值赋给1、2或3。此外,您需要将字符串从input转换为int Try some simple changes. 尝试一些简单的更改。

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) 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM