python - 如何在Python中找到列表的中位数

标签 python

我正在尝试找到列表的中位数。我已经尝试了两种方法,但都不起作用(我已经导入了我需要的内容,并且列表就在那里) selfies 是列表的名称

def median():
    return numpy.median(numpy.array(selfies))

这是错误

ret = umr_sum(arr, axis, dtype, out, keepdims)

TypeError: cannot perform reduce with flexible type

另一种方式是

def median():
    med = statistics.median(selfies)
    return med

错误是

return (data[i - 1] + data[i])/2

TypeError: unsupported operand type(s) for /: 'str' and 'int'

提前谢谢

最佳答案

用户9123您好,

Medain()函数的主要用途

<小时/>

该模块提供用于计算数值(实值)数据的数学统计的函数。

注意除非另有明确说明,否则这些函数支持 int、float、decimal.Decimal 和fractions.Fraction。目前不支持其他类型的行为(无论是否在数字塔中)。混合类型也是未定义的并且依赖于实现。如果您的输入数据由混合类型组成,您可以使用 map() 来确保结果一致,例如 map ( float ,输入数据)。

你的问题

<小时/>

当您对字符串使用此函数时,有时它无法正常工作,所以我建议您使用自定义函数。我在下面的代码中给出了解决方案。

解释函数Median()

<小时/>

statistics.median(数据)

使用常见的“中间两个平均值”方法返回数值数据的中位数(中间值)。如果数据为空,则会引发统计错误。数据可以是序列或迭代器。

中位数是中心位置的可靠衡量标准,受数据中异常值的影响较小。当数据点数量为奇数时,返回中间的数据点:

问题的解决方案

<小时/>

如果您将此函数用于数值,请尝试下面的代码,

def getMedian(numericValues):
  theValues = sorted(numericValues)

  if len(theValues) % 2 == 1:
    return theValues[(len(theValues)+1)/2-1]
  else:
    lower = theValues[len(theValues)/2-1]
    upper = theValues[len(theValues)/2]
    return (float(lower + upper)) / 2 


print getMedian([0,1,2,3,4,5]) # output = 2.5

如果您对字符串使用中值函数,请尝试下面的代码,

def medianFind(mystring):
    return mystring[(len(mystring)-1)/2]  #len returns the length of the string

print medianFind("vmr")  #prints m

希望我的回答对您有帮助。
如果有任何疑问,请发表评论。

关于python - 如何在Python中找到列表的中位数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45003783/

相关文章:

python - 继承时需要初始化父类吗?

python - 数据库 API : How to deal with multi where condition in Python

python - 需要帮助并行化 python 中的循环

python - 你如何从 Django PostgreSQL ArrayField 中获取字符串?

python - 插入排序 Python

python - lxml.etree : Start tag expected, '<' 未找到,第 1 行,第 1 列

python - Django 测试权限中的 ValueError

python - 属性错误 : 'module' object has no attribute 'graphviz_layout' with networkx 1. 11

python - 打印枚举类的所有成员名称

Python递归和返回