我有兩個文件,我想從文件1中提取一些值,像這樣的關鍵:提取物:Python字典,有多個值
File1:
2 word1
4 word2
4 word2_1
4 word2_2
8 word5
8 word5_3
File 2:
4
8
我想是提取每行開始的4 8(來自文件2),他們很多。 所以通常如果只有一行匹配我會使用Python字典,一個關鍵的一個元素很容易!但是現在我有多個元素匹配到同一個鍵,我的腳本只會提取最後一個元素(顯然,隨着它的繼續它將擦除以前的元素!)。 所以我得到這不是如何工作,但我不知道,如果有人可以幫助我開始,我會很高興。
這裏是我的「正常」代碼:
gene_count = {}
my_file = open('file1.txt')
for line in my_file:
columns = line.strip().split()
gene = columns[0]
count = columns[1:13]
gene_count[gene] = count
names_file = open('file2.txt')
output_file = open('output.txt', 'w')
for line in names_file:
gene = line.strip()
count = gene_count[gene]
output_file.write('{0}\t{1}\n'.format(gene,"\t".join(count)))
output_file.close()
更新了我的答案 – OregonTrail 2014-09-03 07:43:06