-
2021-01-29 04:53:38
中位数:中位数是一组数字中的中间数。此代码计算包含数字的列表的中位数:
我们定义一个数字列表并计算列表的长度。要查找中位数,我们首先使用sort()函数按升序排序列表。
现在我们通过检查剩余数量来检查数字是偶数还是奇数。如果数字是偶数,我们在列表中找到2个中间元素并获得它们的平均值以将其打印出来。但如果数字是奇数,我们在列表中找到中间元素并将其打印出来。
# Python program to print
# median of elements
# list of elements to calculate median
n_num = [1, 2, 3, 4, 5]
n = len(n_num)
n_num.sort()
if n % 2 == 0:
median1 = n_num[n//2]
median2 = n_num[n//2 - 1]
median = (median1 + median2)/2
else:
median = n_num[n//2]
print("Median is: " + str(median))
输出:Median is: 3
更多相关内容 -
Python实现求中位数
2020-08-25 16:22:35使用python的内置方法list.sorted()对序列进行排序取中位数 实现 设数据为test: #作者:FarryNiu test = [5,5,6,4,5,4,7,1,10,2,11,10,10] #对test进行升序排列 print(sorted(test)) #偶数 if len(test)%2 == 0: ...展开全文 -
在Python中查找列表的中位数
2020-12-28 21:56:55Python 3.4有statistics.median :返回数字数据的中位数(中间值)。当数据点数为奇数时,返回中间数据点。 当数据点的数量是偶数时,通过取两个中间值的平均值来插值中值:>>> median([1, 3, 5]) 3 >>...Python 3.4有statistics.median :
返回数字数据的中位数(中间值)。
当数据点数为奇数时,返回中间数据点。 当数据点的数量是偶数时,通过取两个中间值的平均值来插值中值:
>>> median([1, 3, 5]) 3 >>> median([1, 3, 5, 7]) 4.0
用法:
import statistics items = [1, 2, 3, 6, 8] statistics.median(items) #>>> 3
types也很小心:
statistics.median(map(float, items)) #>>> 3.0 from decimal import Decimal statistics.median(map(Decimal, items)) #>>> Decimal('3')
对于python-2.x :
使用numpy.median()来创build一个单行的函数:
>>> from numpy import median >>> median([1, -4, -1, -1, 1, -3]) -1.0
或者, 写一个函数 :
def median(lst): n = len(lst) if n < 1: return None if n % 2 == 1: return sorted(lst)[n//2] else: return sum(sorted(lst)[n//2-1:n//2+1])/2.0
>>> median([-5, -5, -3, -4, 0, -1]) -3.5
对于python-3.x ,使用statistics.median :
>>> from statistics import median >>> median([5, 2, 3, 8, 9, -2]) 4.0
sorted()函数对此非常有帮助。 使用sorting后的函数对列表进行sorting,然后简单地返回中间值(或者如果列表中包含偶数个元素,则平均中间两个值)。
def median(lst): sortedLst = sorted(lst) lstLen = len(lst) index = (lstLen - 1) // 2 if (lstLen % 2): return sortedLst[index] else: return (sortedLst[index] + sortedLst[index + 1])/2.0
这是一个更清洁的解决scheme
def median(lst): quotient, remainder = divmod(len(lst), 2) if remainder: return sorted(lst)[quotient] return sum(sorted(lst)[quotient - 1:quotient + 1]) / 2.
注意:答案已更改,以在意见中joinbuild议。
如果需要更快的平均运行时间,您可以尝试快速selectalgorithm。 QuickSelect的平均(和最好)的情况下性能O(n) ,虽然它可以在糟糕的一天结束O(n²) 。
这是一个随机select的支点的实现:
import random def select_nth(n, items): pivot = random.choice(items) lesser = [item for item in items if item < pivot] if len(lesser) > n: return select_nth(n, lesser) n -= len(lesser) numequal = items.count(pivot) if numequal > n: return pivot n -= numequal greater = [item for item in items if item > pivot] return select_nth(n, greater)
你可以简单地把它变成一个find中位数的方法:
def median(items): if len(items) % 2: return select_nth(len(items)//2, items) else: left = select_nth((len(items)-1) // 2, items) right = select_nth((len(items)+1) // 2, items) return (left + right) / 2
这是非常优化的,但即使是优化的版本也不可能超过Tim Sort(CPython的内置sort ),因为这非常快 。 我已经尝试过,我输了。
您可以使用list.sort来避免创build新的列表,并对列表进行sorted和sorting。
你也不应该使用list作为variables名,因为它会影响python自己的列表 。
def median(l): half = len(l) // 2 l.sort() if not len(l) % 2: return (l[half - 1] + l[half]) / 2.0 return l[half]
def median(array): """Calculate median of the given list. """ # TODO: use statistics.median in Python 3 array = sorted(array) half, odd = divmod(len(array), 2) if odd: return array[half] return (array[half - 1] + array[half]) / 2.0
在这里,我在Codecademy的这个练习中提出:
def median(data): new_list = sorted(data) if len(new_list)%2 > 0: return new_list[len(new_list)/2] elif len(new_list)%2 == 0: return (new_list[(len(new_list)/2)] + new_list[(len(new_list)/2)-1]) /2.0 print median([1,2,3,4,5,9])
中值函数
def median(midlist): midlist.sort() lens = len(midlist) if lens % 2 != 0: midl = (lens / 2) res = midlist[midl] else: odd = (lens / 2) -1 ev = (lens / 2) res = float(midlist[odd] + midlist[ev]) / float(2) return res
我为数字列表定义了一个中值函数
def median(numbers): return (sorted(numbers)[int(round((len(numbers) - 1) / 2.0))] + sorted(numbers)[int(round((len(numbers) - 1) // 2.0))]) / 2.0
我在Python中实现了“median of median”algorithm ,这比使用sort()要快一些。 我的解决scheme使用每列15个数字,速度约为5N,比使用每列5个数字的速度约为10N还要快。 最佳速度是~4N,但我可能是错的。
按照Tom的要求,我在这里添加了我的代码,以供参考。 我相信速度的关键部分是每列使用15个数字,而不是5个。
#!/bin/pypy # # TH @stackoverflow, 2016-01-20, linear time "median of medians" algorithm # import sys, random items_per_column = 15 def find_i_th_smallest( A, i ): t = len(A) if(t <= items_per_column): # if A is a small list with less than items_per_column items, then: # # 1. do sort on A # 2. find i-th smallest item of A # return sorted(A)[i] else: # 1. partition A into columns of k items each. k is odd, say 5. # 2. find the median of every column # 3. put all medians in a new list, say, B # B = [ find_i_th_smallest(k, (len(k) - 1)/2) for k in [A[j:(j + items_per_column)] for j in range(0,len(A),items_per_column)]] # 4. find M, the median of B # M = find_i_th_smallest(B, (len(B) - 1)/2) # 5. split A into 3 parts by M, { < M }, { == M }, and { > M } # 6. find which above set has A's i-th smallest, recursively. # P1 = [ j for j in A if j < M ] if(i < len(P1)): return find_i_th_smallest( P1, i) P3 = [ j for j in A if j > M ] L3 = len(P3) if(i < (t - L3)): return M return find_i_th_smallest( P3, i - (t - L3)) # How many numbers should be randomly generated for testing? # number_of_numbers = int(sys.argv[1]) # create a list of random positive integers # L = [ random.randint(0, number_of_numbers) for i in range(0, number_of_numbers) ] # Show the original list # # print L # This is for validation # # print sorted(L)[int((len(L) - 1)/2)] # This is the result of the "median of medians" function. # Its result should be the same as the above. # print find_i_th_smallest( L, (len(L) - 1) / 2)
我有一些浮点值列表的问题。 我最终使用python3 statistics.median中的代码片段,并且正在使用没有导入的float值完美工作。 资源
def calculateMedian(list): data = sorted(list) n = len(data) if n == 0: return None if n % 2 == 1: return data[n // 2] else: i = n // 2 return (data[i - 1] + data[i]) / 2
这是繁琐的方法来find中位数而不使用中median函数:
def median(*arg): order(arg) numArg = len(arg) half = int(numArg/2) if numArg/2 ==half: print((arg[half-1]+arg[half])/2) else: print(int(arg[half])) def order(tup): ordered = [tup[i] for i in range(len(tup))] test(ordered) while(test(ordered)): test(ordered) print(ordered) def test(ordered): whileloop = 0 for i in range(len(ordered)-1): print(i) if (ordered[i]>ordered[i+1]): print(str(ordered[i]) + ' is greater than ' + str(ordered[i+1])) original = ordered[i+1] ordered[i+1]=ordered[i] ordered[i]=original whileloop = 1 #run the loop again if you had to switch values return whileloop
-
python 实现在无序数组中找到中位数
2019-07-16 21:32:111,求一个无序数组的中位数, (若数组是偶数,则中位数是指中间两个数字之和除以2,若数组是奇数,则中位数是指最中间位置。要求:不能使用排序,时间复杂度尽量低 2, 例如: lists = [3, 2, 1, 4] , 中位数为 ...一,问题描述
1,求一个无序数组的中位数, (若数组是偶数,则中位数是指中间两个数字之和除以2,若数组是奇数,则中位数是指最中间位置。要求:不能使用排序,时间复杂度尽量低
2, 例如:
lists = [3, 2, 1, 4] , 中位数为 = (2+3)/2 = 2.5
lists = [3, 1, 2] , 中位数为 2
3, 算法思想:
利用快速排序思想(但是并不是全部使用):任意挑选一个元素,以该元素为key, 划分数组为两个部分,如果左侧数组长度刚好为(n-1)/2, 那么key就为中位数, 若左侧数组长度 < (n-1)/2 , 那么中位数点在右侧,反之,中位数在左侧。然后进入相应的一侧继续寻找中位
平均时间复杂度为O(n)
二,程序
1,
class Solution(object): def findmedian(self, lists): if not lists or len(lists) == 0: return [] n = len(lists) if n % 2 == 0: a = self.partition(lists, n/2, 0, n-1) b = self.partition(lists, n/2-1, 0, n-1) mid = (lists[a]+lists[b])/ (2 * 1.0) return mid else: mid = self.partition(lists, n/2, 0, n-1) return lists[mid] def partition(self, lists, k, start, end): key = lists[start] left, right = start, end while left < right: while left < right and lists[right] > key: right = right - 1 lists[left] = lists[right] while left < right and lists[left] < key: left = left + 1 lists[right] = lists[left] lists[left] = key if left == k: return left elif left > k: return self.partition(lists, k, start, left-1) else: return self.partition(lists, k, left+1, end) if __name__ == "__main__": sol = Solution() lists = [2, 5, 4, 9, 3, 6, 8, 7, 1] # lists = [1, 2] data = sol.findmedian(lists) print("中位数 = %s" % data)
-
python_中位数
2020-04-07 13:21:19# 定义计算中位数的函数get_median(),输入参数为input_list,return值为中位数 def get_median(input_list): input_list.sort() #input_list从小到大排序 #print(input_list) n=len(input_list) #获取input_list... -
python中获取中位数的两种方法
2021-01-11 22:06:18普通方法:对列表进行排序,然后根据长度为奇数或者偶数的不同情况计算中位数def huahua(x):length = len(x)print(length)x.sort()print(x)if (length % 2)== 1:z=length // 2y = x[z]else:y = (x[length//2]+x... -
python求解中位数、均值、众数
2019-02-16 11:19:19首先定义一个数据,在这里我假定为: ...对于有限的数集,可以通过把所有观察值高低排序后找出正中间的一个作为中位数。如果观察值有偶数个,则中位数不唯一,通常取最中间的两个数值的平均数... -
详解Python如何获取列表(List)的中位数
2021-03-18 08:47:31前言中位数是一个可将数值集合划分为相等的上下两部分的一个数值。如果列表数据的个数是奇数,则列表中间那个数据就是列表数据的中位数;如果列表数据的个数是偶数,则列表中间那2个数据的算术平均值就是列表数据的... -
老狗——python求中位数
2020-06-15 11:03:52Python求中位数 每个人都像一辆车。档次有高低,性能有好坏,颜值有高低。但上了路,总归是要向前开。 中位数是一个可将数值集合划分为相等的上下两部分的一个数值。 如果列表数据的个数是奇数,则列表中间那个... -
Python如何获取列表(List)的中位数
2020-12-28 21:57:00前言中位数是一个可将数值集合划分为相等的上下两部分的一个数值。如果列表数据的个数是奇数,则列表中间那个数据就是列表数据的中位数;如果列表数据的个数是偶数,则列表中间那2个数据的算术平均值就是列表数据的... -
python的列表List求均值和中位数实例
2020-11-29 19:54:47import numpy as npa = [2,4,6,8,10]average_a = np.mean(a)median_a = np.median(a)知识补充:python--寻找两个列表的中位数题目描述:给定两个大小为 m 和 n 的有序数组 nums1 和 nums2。请你找出这两个有序数组的... -
python求数字位数的方法
2020-11-22 13:06:38第一种:利用str()函数将数字转化成字符串,再利用len()函数判断位长。1 a=Int(raw_input("the number you want type in:")2 b=len(str(a))3 print b第二种:利用除10取商,通过循环次数判断位数。1 c=02 a=int(raw_... -
Python中的位数,之,判断,数字
2020-11-20 19:54:59运行结果1 ------------------------ input your num 123 输入的数位数为 3 位 运行结果2 ------------------------ input your num 1200000 您输入的位数大于5位,请重新输入 运行结果3 ------------------------ ... -
python 列表的中位数
2017-11-06 14:05:35找出列表的中位数class Solution: def medianFind(self,lst): #先将列表进行排序 lst.sort() half = len(lst)//2 #得到中间序列,~half为负索引,列表元素可能为偶数,需要获取中间两个数 #转化成float,中位... -
如何使用python求平均数、方差、中位数
2020-12-17 22:48:29python求平均数、方差、中位数的例子CalStatistics.pydef getNum(): #获取用户不定长度的输入nums = []iNumStr = input("请输入数字(回车退出):")while iNumStr != "":nums.append(eval(iNumStr))iNumStr = input(... -
python之求中位数
2018-04-26 20:23:28求中位数 给你一个整数列表L, 输出L的中位数(若结果为小数,则保留一位小数)。 例如: L=[0,1,2,3,4] 则输出:2 2.说明 如果列表有奇数个整数,则输出中间那个 如果列表有偶数个整数,则输出中间两个... -
python列表中位数的获取
2018-07-20 15:55:10中位数是一个可将数值集合划分为相等的上下两部分的一个数值。如果列表数据的个数是奇数,则列表中间那个数据就是列表数据的中位数;如果列表数据的个数是偶数,则列表中间那2个数据的算术平均值就是列表数据的中位... -
Python计算中位数 numpy.median
2017-07-04 17:46:48计算沿指定轴的中位数 返回数组元素的中位数其函数接口为:median(a, axis=None, out=None, overwrite_input=False, keepdims=False)其中各参数为: a:输入的数组; axis:计算哪个轴上的中位数,比如... -
【Python】Python程序求中位数
2020-04-14 17:34:31#定义一个函数求中位数 #参数:不定长参数(元组的形式存储) def median(*a): #*a是不定长参数,a以一个元组的形式储存 l=sorted(a) #sorted(a)对列表进行排序,结果返回一个列表 index=len(l)//2 #获取中间值... -
Python中实现控制小数点位数的方法
2019-08-12 20:40:39文章目录一、利用python内置的round()函数二、利用格式化方法三、利用 math 模块里 ceil 和 floor 方法四、超过17位的精度分析 一、利用python内置的round()函数 round()如果只有一个数作为参数,不指定位数的时候,... -
python 计算众数、中位数、分位数、偏度、峰度
2019-12-03 22:50:52python -
python求均值、中位数、众数的方法
2018-05-26 16:18:58首先需要数据源,这里随便写了一个:nums = [1,2,3,4]求均值和中位数均可以使用numpy库的方法: #均值 np.mean(nums) #中位数 np.median(nums)求众数方法一:在numpy中没有直接的方法,但是也可以这样实现:import ... -
python 计算箱线图、中位数、上下四分位数等
2020-09-04 11:24:30#计算中位数 def count_median(lis): if len(lis) % 2 == 0: mid = float((lis[len(lis) / 2] + lis[len(lis) / 2 - 1])) / 2 else: mid = lis[len(lis) / 2] return mid #计算上下四分位数 def count_... -
python如何保留小数点位数
2021-04-26 19:29:51python保留小数点位数的方法:首先新建py文件,输入【a=('%.2f' % a)】即可保留2位小数;然后如果输入【a=('%.4f' % a)】,就保留4位小数;**后也可以输入【a=format(a, '.2f')】来保留小数点位数。0Z8少儿编程网-... -
Python中计算list的中位数
2018-08-17 08:50:02这个解决方法非常巧妙,它利用了取反数和为1的特性,通过列表负索引来获得列表中位数。 对 return (data[half] + data[~half]) / 2 的解释: 排序后得到序列[1,2,3,4,5,6],其列表长度为偶数,中位数由列表中间... -
python怎么取各个数位的数
2020-11-20 22:18:38展开全部a = 12345 取个位 : b = (a / 1) % 10 = a % 10 取十位: b = (a / 10) % 10 取百位: b = (a / 100) % 10 以此2113类推。假设输入的数是5261n, n不为0 n=某数 while n>0。 (n,r) = divmod(n,10) print r 其中... -
python找出3位数的水仙花数
2020-03-07 19:54:27找出3位数的水仙花数 """ 水仙花数也被称为超完全数字不变数、自恋数、自幂数、阿姆斯特朗数,它是一个3位数,该数字每个位上数字的立方之和正好等于它本身,例如:$1^3 + 5^3+ 3^3=153。 """ for num in range(100,... -
python中控制小数位数的3种方法
2020-12-13 20:38:13有三种方法 见如下代码: ...# #############python控制小数位位数############## # 1、使用round()函数 # 所有例子以3.1415926 x = 3.1415926 print(round(x, 3)) # 3表示保留3位小数 # 使用%.nf n表示小数位