2013-03-27 76 views
0

對應值I寫了下面的代碼段:定位特定鍵和在字典

def all_di(fl): 
    dmm = {} 
    for k in range(2): 
     for i in fl: 
      for m in range (len(i)-1): 
       temp = i[m:m+k+1] 
       if temp in dmm: 
        dmm[temp] += 1.0 
       else: 
        dmm[temp] = 1.0 
## return dmm 
    p = raw_input("Enter a 2 AA long seq:") 
    sum = 0 
    for x,y in dmm.iteritems(): 
     if x == p: 
      n1 = y 
    for l,m in dmm.iteritems(): 
     if l[0] == p[0]: 
      sum = sum + m 
    print float(n1)/float(sum) 

all_di(inh) 

如果INH = {'VE':16,'GF':19,'VF':23,'GG' :2}

代碼工作如下:

Enter a 2 AA long seq: VE 

結果將是= 16/(16+23) = 0.41

它是如何工作的:該函數搜索詞典dmm,獲得與在input中輸入的關鍵字類似的關鍵字(此處採用'VE'示例)。它存儲它的值,然後搜索所有具有共同第一個字母的鍵值對,並添加其所有值並返回一個分數。

VE = 16 
**V**E + **V**F = 39 
= 16/39 = 0.41 

我想要什麼:保持功能完好,我想有一個二次字典到迭代的字典中的每一個鍵值對,並存儲它的分數值在不同的字典,即:

new_dict = {'VE' : 0.41, 'GF':0.90,'VF':0.51, 'GG': 0.09} 

我不想刪除print語句,因爲它是我的程序的輸出。然而,我需要new_dict作進一步的工作。

+0

此代碼打印0.25爲示例 – perreal 2013-03-27 01:31:30

回答

1
def all_di(fl,p=0): 
    dmm = {} 
    interactive = p == 0 
    if interactive: 
    p = raw_input("Enter a 2 AA long seq:") 
    if p in fl: 
    numer = fl[p] 
    denom = 0.0 
    for t in fl: 
     if t[0] == p[0]: 
     denom = denom + fl[t] 
    if interactive: 
    print numer/denom 
    return numer/denom 

inh = {'VE':16,'GF':19,'VF':23,'GG' :2} 
all_di(inh) 
new_dict = {x:all_di(inh, x) for x in inh} 
print new_dict 
+0

@ perreal-用任何方法用'raw_input'替換p ='VE'? – 2013-03-27 01:47:20

+0

@ begin.py,再次更新爲僅在交互時打印 – perreal 2013-03-27 02:21:46