这是我的代码。如果我打印变量,它可以正常工作,但如果我返回它们并尝试在其他地方打印它们,则只打印最后一个元素。
def train_data(fname):
#load csv training files
with open (fname) as train:
reader = csv.DictReader(train, delimiter='\t')
for row in reader:
peptide=[row['peptide']]
allele=[row['allele']]
score=[row['score']]
#print(peptide, score, allele)
return [peptide, allele, score]
这是我的csv文件:
peptide score allele
AAAGAEAGKATTEEQ 0.190842 DRB1_0101
AAAGAEAGKATTEEQ 0.006301 DRB1_0301
AAAGAEAGKATTEEQ 0.066851 DRB1_0401
AAAGAEAGKATTEEQ 0.006344 DRB1_0405
AAAGAEAGKATTEEQ 0.035130 DRB1_0701
AAAGAEAGKATTEEQ 0.006288 DRB1_0802
AAAGAEAGKATTEEQ 0.176268 DRB1_0901
AAAGAEAGKATTEEQ 0.042555 DRB1_1101
AAAGAEAGKATTEEQ 0.114855 DRB1_1302
AAAGAEAGKATTEEQ 0.006377 DRB1_1501
AAAGAEAGKATTEEQ 0.006296 DRB3_0101
AAAGAEAGKATTEEQ 0.006313 DRB4_0101
AAAGAEAGKATTEEQ 0.070413 DRB5_0101
我试着像这样打印:
if __name__=='__main__':
p, a, s = train_data('sample.txt')
print(s)
答案 0 :(得分:0)
你只回归一件事。尝试将事物放入列表并返回列表:
def train_data(fname):
peptides = []
alleles = []
scores = []
#load csv training files
with open (fname) as train:
reader = csv.DictReader(train, delimiter='\t')
for row in reader:
peptides.append(row['peptide'])
alleles.append(row['allele'])
scores.append(row['score'])
return peptides, alleles, scores
修改强>
根据您在__main__
中的使用情况,我修改了我的代码以返回三个不同的列表。
答案 1 :(得分:0)
您必须在With
范围之外显示肽,等位基因,得分,否则您将始终获得[None,None,None]
数组:
def train_data(fname):
#load csv training files
peptide= []
allele= []
score = []
with open (fname) as train:
reader = csv.DictReader(train, delimiter='\t')
for row in reader:
peptide.append(row['peptide'])
allele.append(row['allele'])
score.append(row['score'])
return [peptide, allele, score]
我只是猜测你不想[row['allele']]
声明。
现在可以了!
答案 2 :(得分:0)
打印变量 s 只会打印得分变量。
尝试:
print(p, a, s)
如果您希望输出看起来像上面的csv文件:
print(zip(p, a, s))