[英]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.