使用字典

问题描述:

LowKeys = dict(La = 'z', Lb = 'x', Lc = 'c', Ld = 'v', Le = 'b', Lf = 'n', Lg = 'm') 
MidKeys = dict(Ma = 'q', Mb = 'w', Mc = 'e', Md = 'r', Me = 't', Mf = 'y', Mg = 'u') 
HighKeys = dict(Ha = 'i', Hb = 'o', Hc = 'p', Hd = '[', He = ']') 
SharpLowKeys = dict(SLa = 's', SLc = 'f', SLd = 'g', SLf = 'j', SLg = 'k') 
FlatLowKeys = dict(FLa = 'a', FLb = 's', FLd = 'f', FLe = 'g', FLg = 'j') 
SharpMidKeys = dict(SMa = '2', SMc = '4', SMd = '5', SMf = '7', SMg = '8') 
FlatMidKeys = dict(FMa = '1', FMb = '2', FMd = '4', FMe = '5', FMg = '7') 
SharpHighKeys = dict(SHa = '9', SHc = '-', SHd = '=') 
FlatHighKeys = dict(FHa = '8', FHb = '9', FHd = '-', FHe = '=') 

notes = raw_input('Notes: ') 
notes = notes.split() 

我想替换所有出现在Notes和与dict值任何dicts的项目替换列表中的项目。使用字典

例:

notes = La, Ha, Lb 
notes = z, i, x 

有没有办法做到这一点?或者比我想要的更好的方式?

allKeys = {} 
for subdict in (LowKeys, MidKeys, ..., FlatHighKeys): 
    allKeys.update(subdict) 

notes = [allKeys[note] for note in notes] 
+0

你能解释一下这些行可以做什么吗?他们看起来有点难以理解。另外,我们是否可以将这些线路变成更一般的东西,而不是专门用于解决“笔记”问题?谢谢! – FaCoffee 2015-10-26 10:22:32

将字典的所有内容放在一个大字典中,然后使用列表理解从字典中提取适当的值。

+0

你能解释列表理解部分吗? – asqapro 2012-04-23 01:23:41

+0

http://www.python.org/dev/peps/pep-0202/ – 2012-04-23 01:26:31