强制字典值为浮点值

2024-09-27 00:20:43 发布

您现在位置:Python中文网/ 问答频道 /正文

我对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)

提前谢谢


Tags: inforiflineitemcomparehashersnp
1条回答
网友
1楼 · 发布于 2024-09-27 00:20:43

问题在于:

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

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

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

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

相关问题 更多 >

    热门问题