Return 与列表中的中值对应的索引
Return the index corresponding to the median value from a list
我想编写一个函数 median_index(A)
,returns 给定分布 A 的中位数索引(A 是一个包含与每个索引关联的值的列表)。
我已经找到了获取中值的方法,但现在我想知道列表 A 排序时中值所在的位置(索引)。
def median_index(P):
l = sorted(P)
l_len = len(P)
if l_len < 1:
return None
if l_len % 2 == 0 :
return ( l[(l_len-1)/2] + l[(l_len+1)/2] ) / 2.0
else:
return l[(l_len-1)/2]
median_index([0.12,0.04,0.12,0.12,0.2,0.16,0.16,0.08])
结果为 5。 5 是最后位置 0.12。这是我对列表进行排序并计算中位数 0.12 时中位数 0.12 的索引。
您可以使用list.index(element)
我想编写一个函数 median_index(A)
,returns 给定分布 A 的中位数索引(A 是一个包含与每个索引关联的值的列表)。
我已经找到了获取中值的方法,但现在我想知道列表 A 排序时中值所在的位置(索引)。
def median_index(P):
l = sorted(P)
l_len = len(P)
if l_len < 1:
return None
if l_len % 2 == 0 :
return ( l[(l_len-1)/2] + l[(l_len+1)/2] ) / 2.0
else:
return l[(l_len-1)/2]
median_index([0.12,0.04,0.12,0.12,0.2,0.16,0.16,0.08])
结果为 5。 5 是最后位置 0.12。这是我对列表进行排序并计算中位数 0.12 时中位数 0.12 的索引。
您可以使用list.index(element)