代碼低於:[巨蟒]:改變所有的值
d = {'a':0, 'b':0, 'c':0, 'd':0} #at the beginning, all the values are 0.
s = 'cbad' #a string
indices = map(s.index, d.keys()) #get every key's index in s, i.e., a-2, b-1, c-0, d-3
#then set the values to keys' index
d = dict(zip(d.keys(), indices)) #this is how I do it, any better way?
print d #{'a':2, 'c':0, 'b':1, 'd':3}
任何其他方式做到這一點?
PS。上面的代碼只是一個簡單的來展示我的問題。
雅,絕對我知道這一點。我可以保證s中的字符符合d的鍵。感謝你的列舉方式,我碰巧忘記了它。 – Alcott
不錯。你也可以省略括號。 – Owen