2017-08-15 53 views
0

我是python的新手。我有一個問題,我卡住了。信息被保存在許多字典中。變量pos是文件中的一個浮點數,但是python會將其作爲一個字符串讀取。我想這就是爲什麼當compare_positions函數被調用時,我收到此錯誤信息:將字典值強制轉換爲浮點數

Traceback (most recent call last): 
File "anotherPythontry.py", line 167, in <module> 
    iterate_thru(Genes,c,maxp,p) 
File "anotherPythontry.py", line 133, in iterate_thru 
    compare_positions(test_position,maxp,sn,g,p,c) 
File "anotherPythontry.py", line 103, in compare_positions 
    elif (testpos > maxpos and testpos <= maxpos+1): 
TypeError: unsupported operand type(s) for +: 'NoneType' and 'int' 

我試圖使postestposmaxpos浮動,但後來我得到TypeError: float() argument must be a string or a number。我不確定問題是什麼。

下面是代碼:

def hasher(): 
     return collections.defaultdict(hasher) 

Positions = hasher() 
LODs = hasher() 
whole_line = hasher() 
InCommon = hasher() 

def save_info(line): 
    lod = line[7] 
    chr = line[2] 
    pos = line[3] #is a float in the file. Is read as a string though 
    snp = line[1] 
    item = line[10] 
    together = '\t'.join(line) 
    whole_line[item][snp]=together 
    Positions[item][chr][snp]= pos 
    LODs[item][chr][snp]=lod 
    return snp, item 

with open(sys.argv[3],"r") as geneFile: 
    gsnp_list = list() 
    Genes = [] 
    for line in geneFile: 
      line = line.strip().split("\t") 
      type1 = line[0] 
      if "SNP_id" or "Minimum" not in line: 
        if type1 == match: 
          snp,item = save_info(line) 
          gsnp_list.append(snp) 
          if item not in Genes: 
            Genes.append(item) 
# A similar block of code is for another file with phenotypes 

def compare_positions(testpos,maxsnp,gs,gene,p,c): 
    maxpos = Positions[p][c].get(maxsnp) 
    if testpos == maxpos: 
      InCommon[p][c][maxsnp][gene].append(gs) 
    elif (testpos > maxpos and testpos <= maxpos+1): 
      InCommon[p][c][maxsnp][gene].append(gs) 
    elif (testpos < maxpos and testpos >= maxpos-1): 
      InCommon[p][c][maxsnp][gene].append(gs) 

def iterate_thru(Genelist,c,maxp,p): 
    for g in Genelist: 
      for sn in Positions[g][c].keys(): 
        test_position = Positions[g][c].get(sn) 
        compare_positions(test_position,maxp,sn,g,p,c) 

for g in Genes: 
    for c in Positions[g].keys(): 
      chr_SNPlist =() 
      chr_SNPlist = [snp for snp in gsnp_list if snp == Positions[g][c].keys()] 
      maxp = get_max(chr_SNPlist,g,c) 
      iterate_thru(Phenos,c,maxp,g) 

在此先感謝。

回答

1

的問題是在這條線:

test_position = Positions[g][c].get(sn) 

給定請求是不是在字典,返回None作爲不能相比的整數結果。然後將該值傳遞給compare_positions方法,在該方法中進行導致錯誤的比較。

根據您的應用程序,您可以嘗試的默認值,如零:

test_position = Positions[g][c].get(sn, 0) 
+0

感謝您的答覆。我錯誤地沒有添加所有的代碼。正如你所看到的'test_position = Positions [g] [c] .get(sn)'應該在字典中,因爲我正在遍歷'iterate_thru'函數中的鍵。在'save_info'函數中,字典應該進行autovivification。 – NewbieDoo

+0

如果密鑰在字典中,則該密鑰的值必須爲無。如果None是該鍵位置的值,這可能會起作用'test_position =位置[g] [c] .get(sn)或0',其中零值將被返回。 – Alexander

相關問題