我不確定我是否適當地提出問題標題。但是,我試圖解釋下面的問題。如果你能想到這個問題,請建議適當的標題。如何找到兩個列表之間的匹配並根據匹配寫入輸出?
說我有兩種類型的列表數據:
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