2011-08-18 17 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}