代码低于:[巨蟒]:改变所有的值
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