一个值的Python Dictionary索引 [英] Python Dictionary index of a value
本文介绍了一个值的Python Dictionary索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试从字典获取一个值的索引,并且不确定要尝试什么。
I am currently trying to get the index of a value from a dictionary and unsure what to try.
我的字典是:
midi2notes = {
'c':("0","12","24","36","48","60","72","84","96","108","120"),
'des':("1","13","25","37","49","61","73","85","97","109","121"),
'd':("2","14","26","38","50","62","74","86","98","110","122"),
'ees':("3","15","27","39","51","63","75","87","99","111","123"),
'e':("4","16","28","40","52","64","76","88","100","112","124"),
'f':("5","17","29","41","53","65","77","89","101","113","125"),
'ges':("6","18","30","42","54","66","78","90","102","114","126"),
'g':("7","19","31","43","55","67","79","91","103","115","127"),
'aes':("8","20","32","44","56","68","80","92","104","116"),
'a':("9","21","33","45","57","69","81","93","105","117"),
'bes':("10","22","34","46","58","70","82","94","106","118"),
'b':("11","23","35","47","59","71","83","95","107","119")
}
示例:我想获取值 - 从键'c'的60。哪个应该是5.最有效/最快速的方法是什么。
Example: I want to get the index of value-"60" from key- 'c'. Which should be 5. What would be the most efficient/quickest way to go about this.
推荐答案
我会做: p>
I would do:
midi2notes['c'].index('60')
如果没有找到索引,这将引发 ValueError
,但是如果数字通常在元组中,这将很难击败优化的C后端。
This will raise an ValueError
if the index isn't found, but if the numbers are usually in the tuple, it'll be hard to beat the optimized C backend.
>>> midi2notes = {
... 'c':("0","12","24","36","48","60","72","84","96","108","120"),
... 'des':("1","13","25","37","49","61","73","85","97","109","121"),
... 'd':("2","14","26","38","50","62","74","86","98","110","122"),
... 'ees':("3","15","27","39","51","63","75","87","99","111","123"),
... 'e':("4","16","28","40","52","64","76","88","100","112","124"),
... 'f':("5","17","29","41","53","65","77","89","101","113","125"),
... 'ges':("6","18","30","42","54","66","78","90","102","114","126"),
... 'g':("7","19","31","43","55","67","79","91","103","115","127"),
... 'aes':("8","20","32","44","56","68","80","92","104","116"),
... 'a':("9","21","33","45","57","69","81","93","105","117"),
... 'bes':("10","22","34","46","58","70","82","94","106","118"),
... 'b':("11","23","35","47","59","71","83","95","107","119")
... }
>>> midi2notes['c'].index('60')
5
>>> midi2notes['c'].index('180')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: tuple.index(x): x not in tuple
>>>
这篇关于一个值的Python Dictionary索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文