将字典值强制转换为浮点数

时间:2017-08-15 18:52:33

标签: python string dictionary numbers typeerror

我是python的新手。我有问题,而且我被困住了。信息保存在许多词典中。变量pos是文件中的float,但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 个答案:

答案 0 :(得分:1)

问题出在这一行:

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

给定的请求不在字典中,返回None作为无法与整数进行比较的结果。然后将此值传递给compare_positions方法,在该方法中进行比较,导致出现错误。

根据您的应用程序,您可以尝试使用默认值,例如零:

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