[英]How to use a comparison statement on a for loop iterator in a conditional statement?
我正在迭代一个大的(300+列和1 000 000+行).txt文件(制表符分隔)。 文件格式:
species 1 ... sample1(11th col) sample2 .... sampleN(353th col)
species 2 ... 6046 5364 ....
species 3 ... 15422 0 ....
每行是一个物种,从第11栏开始,每列都是一个样本。 对于每个样本,我想知道该样本中有多少物种的值大于0.所以我要做的是迭代每一行,看看哪个样本的值大于0,如果是,则添加1.所以对于每个样本,1的总和是值大于0的行的总量。
为此,我使用以下代码:
samples = []
OTUnumber = []
with open('all.16S.uniq.txt','r') as file:
for i,line in enumerate(file):
columns = line.strip().split('\t')[11:353]
if i == 0: #headers are sample names so first row
samples = columns #save sample names
OTUnumbers = [0 for s in samples] #set starting value as zero
else:
for n,v in enumerate(columns):
if v > 0:
OTUnumber[n] = OTUnumber[n] + 1
else:
continue
result = dict(zip(samples,OTUnumbers))
当我运行这个代码时,我得到以下错误: TypeError: '>' not supported between instances of 'str' and 'int'
if v > 0
则引发此错误。 为什么我不能写这个陈述?
因此,如果列[n]> 0的v我想在该索引处向OTUnumber添加1。 如果v <0我想跳过那一行而不加1(或加0)。
如何使此代码有效?
当我运行这个代码时,我得到以下错误:
TypeError: '>' not supported between instances of 'str' and 'int'
如果v > 0
则引发此错误。 为什么我不能写这个陈述?
正如错误所示,您正在尝试对字符串和int使用比较运算符>
,这是不允许的。 v
是一个字符串,而不是整数。 大概你想使用int(v) > 0
而不是v > 0
,或者开始使用以下内容。
columns = [int(v) for v in line.strip().split('\t')[11:353]]
尝试这个:
samples = []
OTUnumbers = []
with open('all.16S.uniq.txt','r') as file:
for i,line in enumerate(file):
columns = line.strip().split('\t')[11:353]
if i == 0: #headers are sample names so first row
samples = columns #save sample names
OTUnumbers = [0 for s in samples] #set starting value as zero
else:
for n,v in enumerate(columns):
if int(v) > 0:
OTUnumbers[n] = OTUnumbers[n] + 1
else:
continue
result = dict(zip(samples,OTUnumbers))
这基本上是2个修复:
v
为int
OTUnumber
到OTUnumbers
中的所有代码 所以问题是在你的文本文件中有记录是字符串,你的代码试图将一个整数与一个抛出TypeError异常的字符串进行比较
要使代码工作,您可以在比较之前将记录转换为int,即int(v) > 0
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.