在 Python 中查找列表的中位数

编程入门 行业动态 更新时间:2024-10-22 23:13:01
本文介绍了在 Python 中查找列表的中位数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

你如何在 Python 中找到列表的中位数?该列表可以是任意大小,并且不保证数字按任何特定顺序排列.

如果列表包含偶数个元素,则函数应返回中间两个元素的平均值.

以下是一些示例(按显示目的排序):

中值([1]) == 1中位数([1, 1]) == 1中位数([1, 1, 2, 4]) == 1.5中位数([0, 2, 5, 6, 8, 9, 9]) == 6中位数([0, 0, 0, 0, 4, 4, 6, 8]) == 2

解决方案

Python 3.4 有 statistics.median:

返回数值数据的中位数(中间值).

当数据点数为奇数时,返回中间的数据点.当数据点数为偶数时,取两个中间值的平均值来插值中位数:

>>>中位数([1, 3, 5])3>>>中位数([1, 3, 5, 7])4.0

用法:

导入统计项目 = [6, 1, 8, 2, 3]统计.中位数(项目)#>>>3

对于类型也非常小心:

statistics.median(map(float, items))#>>>3.0从十进制导入十进制statistics.median(map(Decimal, items))#>>>十进制('3')

How do you find the median of a list in Python? The list can be of any size and the numbers are not guaranteed to be in any particular order.

If the list contains an even number of elements, the function should return the average of the middle two.

Here are some examples (sorted for display purposes):

median([1]) == 1 median([1, 1]) == 1 median([1, 1, 2, 4]) == 1.5 median([0, 2, 5, 6, 8, 9, 9]) == 6 median([0, 0, 0, 0, 4, 4, 6, 8]) == 2

解决方案

Python 3.4 has statistics.median:

Return the median (middle value) of numeric data.

When the number of data points is odd, return the middle data point. When the number of data points is even, the median is interpolated by taking the average of the two middle values:

>>> median([1, 3, 5]) 3 >>> median([1, 3, 5, 7]) 4.0

Usage:

import statistics items = [6, 1, 8, 2, 3] statistics.median(items) #>>> 3

It's pretty careful with types, too:

statistics.median(map(float, items)) #>>> 3.0 from decimal import Decimal statistics.median(map(Decimal, items)) #>>> Decimal('3')

更多推荐

在 Python 中查找列表的中位数

本文发布于:2023-11-29 16:39:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1646966.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:中位数   列表   Python

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!