2011-08-18 18 views
3

代码低于:[巨蟒]:改变所有的值

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。上面的代码只是一个简单的来展示我的问题。

回答

9

像这样的东西可能使你的代码更易读:

dict([(x,y) for y,x in enumerate('cbad')]) 

但是,你应该提供更多的细节你真正想做的事情。如果s中的字符不符合d的密钥,您的代码可能会失败。所以d只是一个容器的键和值并不重要。为什么不从这种情况下的列表开始?

+0

雅,绝对我知道这一点。我可以保证s中的字符符合d的键。感谢你的列举方式,我碰巧忘记了它。 – Alcott

+2

不错。你也可以省略括号。 – Owen

0
for k in d.iterkeys(): 
    d[k] = s.index[k] 

或者,如果你还不知道在字符串中的字母:

d = {} 
for i in range(len(s)): 
    d[s[i]]=i 
+0

感谢您的iterkeys,哈。 – Alcott

2

什么

d = {'a':0, 'b':0, 'c':0, 'd':0} 
s = 'cbad' 
for k in d.iterkeys(): 
    d[k] = s.index(k) 

?它不再是函数式编程,但应该是更高性能和更pythonic,也许:-)。

编辑:使用python字典,推导的函数变种(需要Python 2.7+或3+):

d.update({k : s.index(k) for k in d.iterkeys()}) 

甚至

{k : s.index(k) for k in d.iterkeys()} 

如果一个新的字典是好的!

+0

是的,你说得对,但我更喜欢FP方式。 – Alcott

+0

好吧,我的第二或第三个建议? –

+0

你好,我想选第三个。谢谢你 – Alcott

0

使用更新()字典的方法:

d.update((k,s.index(k)) for k in d.iterkeys()) 
0

您选择合适的方式,但认为没有必要建立字典,然后修改它,如果你在同一时间做这种能力:

​​
+0

是的,绝对你是对的,谢谢朋友。 – Alcott

0
字典

理解为Python 2.7和以上

{key : indice for key, indice in zip(d.keys(), map(s.index, d.keys()))} 
1

另一个衬里:

dict([(k,s.index(k)) for (k,v) in d.items()]) 
+0

是啊,相当不错。 – Alcott

0
>>> d = {'a':0, 'b':0, 'c':0, 'd':0} 
>>> s = 'cbad' 
>>> for x in d: 
     d[x]=s.find(x) 
>>> d 
    {'a': 2, 'c': 0, 'b': 1, 'd': 3}