[英]How do I efficiently get the index and value for a key from SortedDict?
Given a collection that is ordered and keyed (like OrderedDict or SortedContainers SortedDict) I want to do the following: 给定一个有序且有键的集合(例如OrderedDict或SortedContainers SortedDict),我想执行以下操作:
d['first'] = 'hi'
d['second'] = 'there'
d['third'] = 'world'
(ix, value) = d.get_index_and_value('second')
assert d.iloc[ix + 1] == 'third'
# or list(d.keys())[ix + 1] with OrderedDict
however I cannot see an efficient way to get both the index and the value given a key ( (ix, value) = d.get_index_and_value('second')
). 但是我看不到一种有效的方式来获取给定键的索引和值(
(ix, value) = d.get_index_and_value('second')
)。
Is this possible with SortedDict, or another container? 使用SortedDict或其他容器是否可能?
In practice, my keys are a sortable collection (dates) if that means there is a better container I could use. 在实践中,如果这意味着我可以使用更好的容器,那么我的密钥就是一个可排序的集合(日期)。
You can use the index
method of keys
: 您可以使用
keys
的index
方法:
ix, value = d.keys().index('second'), d['second']
this will return 这将返回
(1, 'there')
If you don't want to repeat yourself, you can make this a function, or extend OrderedDict
to include this as a method: 如果您不想重复自己,可以使它成为一个函数,或者扩展
OrderedDict
以将其作为方法包括在内:
def get_index_and_value(d, key):
return d.keys().index(key), d[key]
print(get_index_and_value(d, 'second')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.