问题
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"
, returnfrequency
and get261.6255653006
.input:
261.6255653006
, returnmidinumber
and get60
input:
60
, returnmidinote
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