我正在处理Midi音符,midi编号和频率.我应该使用python中的哪种列表来引用任何一个属性并获取其他属性?
I'm working with midi note, midi number, and frequency. What kind of list in python should I use to refer to any one attribute and get the other attributes?
例如:
-
输入:"C3",返回frequency并获得261.6255653006.
输入:261.6255653006,返回midinumber并获得60
输入:60,返回midinote并获得"C3"
我将使用什么语法,函数,对象或列表类型?
what syntax, functions, objects, or list type would I use?
推荐答案就像我在评论中说的那样,您可能正在寻找元组字典.示例:
Like I said in the comments, a dictionary of tuples is what you're probably looking for. Example:
data = {'C3': ('frequency', 261.6255653006), 261.6255653006: ('midinumber', 60), 60: ('midinote', 'C3'), }要验证您的输入,您可以执行以下操作:
To validate your input you can do:
input = raw_input() try: key = float(input) except ValueError: key = input try: value = data[key] except KeyError: print "Invalid input. Valid keys are: " + ', '.join(data.keys()) else: #input was valid, so value == data[key]对索引进行索引就像对列表进行索引一样.但是,它们是不可变的,这意味着您无法更改它们或将新项目添加到它们.我相信您的情况就是如此.
Tuples are indexed just like lists are. However, they are immutable which means you can't change them or append new items to them. And I believe that's desired in your case.
字典通过键索引,例如data['C3']返回('frequency', 261.6255653006),而data['C3'][0]返回'frequency'.
Dictionaries are indexed by keys, for example data['C3'] returns ('frequency', 261.6255653006) and data['C3'][0] returns 'frequency'.
更多推荐
python如何创建可互换值列表?
发布评论