简体   繁体   English

从字典中获取价值指数

[英]Get value indices from dictionary

I have an OrderedDict : 我有一个OrderedDict

from collections import OrderedDict
d = OrderedDict([('r', 1), ('s', 5), ('a', 3), ('n', 7), ('y', 2)])

I'd like to get indices of dictionary values according to values range. 我想根据值范围获取字典值的索引。 For example, indices of dictionary d should be array (or np.array ), like following: 例如,字典d索引应为array(或np.array ),如下所示:

indices
array([ 0, 3, 2, 4, 1 ], dtype=int64) 

index 4 is a biggest value in dictionary, index 0 is smallest value 索引4是字典中的最大值,索引0是最小值

I tried : 我试过了 :

indices = np.argsort(d.values)

You can use a list comprehension to implement this: 您可以使用列表推导来实现此目的:

>>> values = d.values()
>>> sorted_values = sorted(values)
>>> [sorted_values.index(item) for item in values]
[0, 3, 2, 4, 1]

Since you've tried with argsort: 由于您已尝试使用argsort:

np.argsort(d.values()).argsort()
Out[50]: array([0, 3, 2, 4, 1], dtype=int64)

So argsort does not actually return their orders but it returns the indices that would sort that array. 因此argsort实际上并不返回其顺序,而是返回将对该数组进行排序的索引。 Calling argsort on that result does what you want. 对该结果调用argsort可以满足您的需求。

The other answer is nice and simple but is O(n^2) as each .index is O(n) . 另一个答案很好也很简单,但是是O(n^2)因为每个.indexO(n) You can precompute the indices in a dictionary so that the index lookups are O(1) , making the whole thing O(nlogn) as the sort is the most expensive part. 您可以预先计算字典中的索引,以使索引查找为O(1) ,使整个O(nlogn)成为排序最昂贵的部分。 If d is large enough this will be a very important difference. 如果d足够大,这将是非常重要的区别。

>>> from itertools import izip
>>> indices = dict(izip(sorted_values, xrange(len(d))))
>>> indices
{1: 0, 2: 1, 3: 2, 5: 3, 7: 4}
>>> [indices[v] for v in d.itervalues()]
[0, 3, 2, 4, 1]

Here I've used xrange instead of range , izip instead of zip , and itervalues instead of values for memory efficiency. 在这里,我使用xrange代替rangeizip代替zip ,并使用itervalues代替values以提高内存效率。

最后,我忘了将()放在values之后,所以我使用了indices = np.argsort(d.values())

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM