将字典值强制转换为浮点数
问题描述:
我是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'
我试图使pos
,testpos
,maxpos
浮动,但后来我得到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)
在此先感谢。
答
的问题是在这条线:
test_position = Positions[g][c].get(sn)
给定请求是不是在字典,返回None
作为不能相比的整数结果。然后将该值传递给compare_positions
方法,在该方法中进行导致错误的比较。
根据您的应用程序,您可以尝试的默认值,如零:
test_position = Positions[g][c].get(sn, 0)
感谢您的答复。我错误地没有添加所有的代码。正如你所看到的'test_position = Positions [g] [c] .get(sn)'应该在字典中,因为我正在遍历'iterate_thru'函数中的键。在'save_info'函数中,字典应该进行autovivification。 – NewbieDoo
如果密钥在字典中,则该密钥的值必须为无。如果None是该键位置的值,这可能会起作用'test_position =位置[g] [c] .get(sn)或0',其中零值将被返回。 – Alexander