使用NumPy查找元组列表的第二个元素的中位数 [英] Using NumPy to Find Median of Second Element of List of Tuples
问题描述
假设我有一个元组列表,如下所示:
Let's say I have a list of tuples, as follows:
list = [(a,1), (b,3), (c,5)]
我的目标是使用元组的第二个元素来获取元组列表中位数的第一个元素.在上述情况下,我希望输出b,因为中位数为3.我尝试将NumPy与以下代码一起使用,但无济于事:
My goal is to obtain the first element of the median of the list of tuples, using the tuples' second element. In the above case, I would want an output of b, as the median is 3. I tried using NumPy with the following code, to no avail:
import numpy as np
list = [('a',1), ('b',3), ('c',5)]
np.median(list, key=lambda x:x[1])
推荐答案
您可以像这样计算中位数:
You could calculate the median like this:
np.median(dict(list).values())
# in Python 2.7; in Python 3.x it would be `np.median(list(dict(list_of_tuples).values()))`
首先将您的列表转换为字典,然后计算其值的中位数.
That converts your list to a dictionary first and then calculates the median of its values.
当您想要获取实际的密钥时,可以这样做:
When you want to get the actual key, you can do it like this:
dl = dict(list) #{'a': 1, 'b': 3, 'c': 5}
dl.keys()[dl.values().index(np.median(dl.values()))]
将打印'b'
.假设中位数在列表中,否则将抛出ValueError
.因此,可以使用@Anand S Kumar的答案中的示例,像这样使用try/except
:
which will print 'b'
. That assumes that the median is in the list, if not a ValueError
will be thrown. You could therefore then use a try/except
like this using the example from @Anand S Kumar's answer:
import numpy as np
l = [('a',1), ('b',3), ('c',5), ('d',22),('e',11),('f',3)]
# l = [('a',1), ('b',3), ('c',5)]
dl = dict(l)
try:
print(dl.keys()[dl.values().index(np.median(dl.values()))])
except ValueError:
print('The median is not in this list. Its value is ',np.median(dl.values()))
print('The closest key is ', dl.keys()[min(dl.values(), key=lambda x:abs(x-np.median(dl.values())))])
对于第一个列表,您将获得:
For the first list you will then obtain:
中位数不在此列表中.它的值为4.0
The median is not in this list. Its value is 4.0
最接近的键是f
在您的示例中,它仅打印:
for your example it just prints:
b
这篇关于使用NumPy查找元组列表的第二个元素的中位数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!