python how to create list of interchangeable values?

可紊 提交于 2021-01-28 07:30:20

问题


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?

for example:

  • input: "C3", return frequency and get 261.6255653006.

  • input: 261.6255653006, return midinumber and get 60

  • input: 60, return midinote and get "C3"

what syntax, functions, objects, or list type would I use?


回答1:


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.

Dictionaries are indexed by keys, for example data['C3'] returns ('frequency', 261.6255653006) and data['C3'][0] returns 'frequency'.



来源:https://stackoverflow.com/questions/23460155/python-how-to-create-list-of-interchangeable-values

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!