2012-04-23 117 views
2
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 

有沒有辦法做到這一點?或者比我想要的更好的方式?

回答

3
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

1

將字典的所有內容放在一個大字典中,然後使用列表理解從字典中提取適當的值。

+0

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

+0

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