我在 python 中更新字典中的值时遇到问题。我正在尝试更新单个第一级键的嵌套值(作为 int 或列表),但我更新了所有第一级键的值。
我首先创建字典:
kmerdict = {}
innerdict = {'endcover':0, 'coverdict':{}, 'coverholder':[], 'uncovered':0, 'lowstart':0,'totaluncover':0, 'totalbases':0}
for kmer in kmerlist: # build kmerdict
kmerdict [kmer] = {}
for chrom in fas: #open file and read line
chromnum = chrom[3:-3]
kmerdict [kmer][chromnum] = innerdict
然后我从一个列表(fas,未显示)中遍历染色体(作为纯文本文件),并以 7mer 字符串(k=7)作为键。如果该键在我正在寻找的键列表中(kmerlist)并尝试使用它来引用嵌套在字典中的单个值:
for chrom in fas: #open file and read line
chromnum = chrom[3:-3]
p = 0 #chromosome position counter
thisfile = "/var/store/fa/" + chrom
thischrom = open(thisfile)
thischrom.readline()
thisline = thischrom.readline()
thisline = string.strip(thisline.lower())
l=0 #line counter
workline = thisline
while(thisline):
if len(workline) > k-1:
thiskmer = ''
thiskmer = workline[0:k] #read five bases
if thiskmer in kmerlist:
thisuncovered = kmerdict[thiskmer][chromnum]['uncovered']
thisendcover = kmerdict[thiskmer][chromnum]['endcover']
thiscoverholder = kmerdict[thiskmer][chromnum]['coverholder']
if p >= thisendcover:
thisuncovered += (p - thisendcover)
thisendcover = ((p+k) + ext)
thiscoverholder.append(p)
elif p < thisendcover:
thisendcover = ((p+k) + ext)
thiscoverholder.append(p)
print kmerdict[thiskmer]
p += 1
workline = workline[1:]
else:
thisline = thischrom.readline()
thisline = string.strip(thisline.lower())
workline = workline+thisline
l+=1
print kmerdict
但是当我打印字典时,所有“thiskmer”级别都将使用相同的值进行更新。我的字典不是很好,我看不到我的方式的错误,但它们是深刻的!任何人都可以启发我吗?
希望我已经足够清楚了。我一直在修改这段代码太久了:(