我正在尝试编写一个脚本,它将获取10个数据文件,逐行读取它们,并为文件中的第一个(基因)和第三个(值)项创建一个字典,然后将所有这些合并到一个输出文件中,其中第12列显示10个重复项之间的平均值。(我将对几个不同的示例执行此操作,每个示例有10个副本。)我尝试使用for循环和range函数自动生成文件名、字典名等。因为我确信这是一种比编写10次字典代码更干净的方法。但是,我对编码还不熟悉,在代码的第11行('gene{0}key'.format(I)=[])的第11行一直收到“SyntaxError:cannotassign to function call”,而且我确信对于其他几行结构相同的代码,它也会这样做。如果有人知道我做错了什么,我很想知道是什么!提前谢谢你!在
#!/usr/bin/env ipython
import re
import itertools
import numpy
sample = raw_input('sample: ')
for i in range(10):
filename = sample+'_rand{0}.genes.tajD'.format(i)
'gene{0}key'.format(i) = []
'taj{0}value'.format(i) = []
with open(filename, 'r') as data:
for line in data:
line = line.strip().split('\t')
gene, taj = line[0], line[3]
'gene{0}key'.format(i).append(gene)
'taj{0}value'.format(i).append(taj)
'dic{0}'.format(i) = dict(itertools.izip('gene{0}key'.format(i),'taj{0}value'.format(i)))
outfilename = sample+'_tajD.genes.all'
with open(sample+'_rand0.genes.tajD', 'r') as genes, open(outfilename, 'w') as outfile :
for line in genes :
line = line.strip().split('\t')
mastergene = line[0]
for i in range(10):
'value{0}'.format(i) = 'dic{0}'.format(i)[mastergene]
allrand = [value0, value1, value2, value3, value4, value5, value6, value7, value8, value9]
avg = numpy.mean(allrand)
outfile.write(mastergene + '\t' + value0 + '\t' + value1 + '\t' + value2 +'\t' + value3 + '\t' + value4 + '\t' + value5 + '\t' + value6 + '\t' + value7 + '\t' + value8 + '\t' + value9 + '\t' + avg + '\n')
这是新程序员尝试使用的典型反模式。您需要创建十个名为
^{pr2}$gene1key
、gene2key
、gene3key
等的变量。正确的方法是使用一个列表或字典,然后使用i
作为键索引。重写代码以使其语法正确的最简单方法是:代码可以进一步简化。例如,由于genekeys和tajvalues只用于创建
dictionaries
,所以您可以直接填充dict而不需要存储中间值。您可以使values
成为一个列表,因此您不必在numpy.mean
和outfile.write
期间显式地处理每个列表。在相关问题 更多 >
编程相关推荐