例如
组织列表:
aa b2 c d
映射:
aa 1
b2 2
d 3
c 4
基因列表:
1 2 4 3
Python 的实现方式是什么?假设 org_list 和映射在文件 org_list.txt 和 mapping.txt 中,而 gen_list 将写入 gen_list.txt
顺便说一句,您认为哪种语言可以非常简单地实现这一点?
请您参考如下方法:
只需使用 list comprehension 遍历列表:
gen_list = [mapping[i] for i in org_list]
演示:
>>> org_list = ['aa', 'b2', 'c', 'd']
>>> mapping = {'aa': 1, 'b2': 2, 'd': 3, 'c': 4}
>>> [mapping[i] for i in org_list]
[1, 2, 4, 3]
如果文件中有此数据,请首先在内存中构建映射:
with open('mapping.txt') as mapfile:
mapping = {}
for line in mapfile:
if line.strip():
key, value = line.split(None, 1)
mapping[key] = value
然后从输入文件构建输出文件:
with open('org_list.txt') as inputfile, open('gen_list.txt', 'w') as outputfile:
for line in inputfile:
try:
outputfile.write(mapping[line.strip()] + '\n')
except KeyError:
pass # entry not in the mapping
