问题描述
我有一个,其中列出了键值,值对。我想计算索引 i
,以便 i
th键匹配给定的值。例如:
I have a collections.OrderedDict
with a list of key, value pairs. I would like to compute the index i
such that the i
th key matches a given value. For example:
food = OrderedDict([('beans',33),('rice',44),('pineapple',55),('chicken',66)])
我想从关键鸡
到索引3,或从键$ rice
到索引1.我现在可以用
I want to go from the key chicken
to the index 3, or from the key rice
to the index 1. I can do this now with
food.keys().index('rice')
但有什么办法可以利用 OrderedDict
的能力,通过键名快速查找?否则看起来索引发现是O(N)而不是O(log N),我有很多项目。
but is there any way to leverage the OrderedDict
's ability to look things up quickly by key name? Otherwise it seems like the index-finding would be O(N) rather than O(log N), and I have a lot of items.
我想我可以通过自己的索引来手动执行:
I suppose I can do this manually by making my own index:
>>> foodIndex = {k:i for i,k in enumerate(food.keys())}
>>> foodIndex
{'chicken': 3, 'rice': 1, 'beans': 0, 'pineapple': 2}
但我希望可能有一些东西内置到 OrderedDict
。
but I was hoping there might be something built in to an OrderedDict
.
推荐答案
基本上没有。 OrderedDict可以通过使用正常的无序字体在键盘下快速查找事物的能力。订单信息分开存储在双向链表中。正因为如此,没有办法直接从关键到它的索引。 OrderedDict中的顺序主要用于迭代;一键不会知道自己的订单。
Basically, no. OrderedDict gets its ability to look things up quickly by key name just by using a regular, unordered dict under the hood. The order information is stored separately in a doubly linked list. Because of this, there's no way to go directly from the key to its index. The order in an OrderedDict is mainly intended to be available for iteration; a key does not "know" its own order.
这篇关于在Python OrderedDict中获取关键索引?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!