我不确定我是否适当地提出问题标题。但是,我试图解释下面的问题。如果你能想到这个问题,请建议适当的标题。如何找到两个列表之间的匹配并根据匹配写入输出?
说我有两种类型的列表数据:
list_headers = ['gene_id', 'gene_name', 'trans_id']
# these are the features to be mined from each line of `attri_values`
attri_values =
['gene_id "scaffold_200001.1"', 'gene_version "1"', 'gene_source "jgi"', 'gene_biotype "protein_coding"']
['gene_id "scaffold_200001.1"', 'gene_version "1"', 'trans_id "scaffold_200001.1"', 'transcript_version "1"', 'exon_number "1"', 'gene_source "jgi"', 'gene_biotype "protein_coding"', 'transcript_source "jgi"', 'transcript_biotype "protein_coding"', 'exon_id "scaffold_200001.1.exon1"', 'exon_version "1"']
['gene_id "scaffold_200002.1"', 'gene_version "1"', 'trans_id "scaffold_200002.1"', 'transcript_version "1"', 'exon_number "3"', 'gene_source "jgi"', 'gene_biotype "protein_coding"', 'transcript_source "jgi"', 'transcript_biotype "protein_coding"', 'exon_id "scaffold_200002.1.exon3"', 'exon_version "1"']
我努力使基础上list in the header
和attribute in the attri_values
的匹配表。
output = open('gtf_table', 'w')
output.write('\t'.join(list_headers) + '\n') # this will first write the header
# then I want to read each line
for values in attri_values:
for list in list_headers:
if values.startswith(list):
attr_id = ''.join([x for x in attri_values if list in x])
attr_id = attr_id.replace('"', '').split(' ')[1]
output.write('\t' + '\t'.join([attr_id]))
elif not values.startswith(list):
attr_id = 'NA'
output.write('\t' + '\t'.join([attr_id]))
output.write('\n')
问题:是,当从list of list_headers
匹配字符串values of attri_values
发现一切运作良好,但是当没有比赛有很多重复的“NA”的。
最终预期的结果:
gene_id gene_name trans_id
scaffold_200001.1 NA NA
scaffold_200001.1 NA scaffold_200001.1
scaffold_200002.1 NA scaffold_200002.1
帖子编辑: 这个问题我怎么写了我的elif
(因为每一个非匹配会写“NA”)。我试图以不同的方式移动NA
的条件,但没有成功。 如果我删除elif
得到它作为第输出(NA
丢失):
gene_id gene_name trans_id
scaffold_200001.1
scaffold_200001.1 scaffold_200001.1
scaffold_200002.1 scaffold_200002.1
感谢您的回答。使用字典会很复杂,因为这些只是大数据的一小部分。我认为简单的嵌套for循环会解决它。顺便说一句,我得到'类型错误'result = searchHeader(list_headers,attri_values)' – everestial007
@ everestial007我的坏!我应该将'title'而不是'list_headers'传递给函数:'result = searchHeader(title,attri_values)'。这可能是深夜编写代码的结果:P? – direprobs
我了解电脑太多和/或困倦的后果。顺便说一句,代码仍然无法为我解决问题。我试着改变一些像**而不是'如果在x中的标题:'我认为它应该'如果x.startswith(标题)'原因在那里将不会有一个命中列表比较,除非所有字符串匹配* *。我也尝试改变其他的东西,但没有运气。你能给我一个完整的工作例子吗? - 这是可能的。请注意这个问题,以便更多关注这个问题。 – everestial007