例如
组织列表:
aa b2 c d
映射:
aa 1
b2 2
d 3
c 4
gen_list:
1 2 4 3
Python 的实现方式是什么?假设 org_list 和映射在 filesorg_list.txt
和mapping.txt
中,而 gen_list 将被写入gen_list.txt
顺便说一句,您希望哪种语言很容易实现这一点?
例如
组织列表:
aa b2 c d
映射:
aa 1
b2 2
d 3
c 4
gen_list:
1 2 4 3
Python 的实现方式是什么?假设 org_list 和映射在 filesorg_list.txt
和mapping.txt
中,而 gen_list 将被写入gen_list.txt
顺便说一句,您希望哪种语言很容易实现这一点?
只需使用列表推导遍历列表:
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
这是您的情况的解决方案。
with open('org_list.txt', 'rt') as inp:
lines = inp.read().split()
org_list = map(int, lines)
with open('mapping.txt', 'rt') as inp:
lines = inp.readlines()
mapping = dict(line.split() for line in lines)
gen_list = (mapping[i] for i in org_list) # Or you may use `gen_list = map(mapping.get, org_list)` as suggested in another answers
with open('gen_list.txt', 'wt') as out:
out.write(' '.join(gen_list))
我认为 Python 足够优雅地处理这种情况。
另一种方式:
In [1]: start = [1,2,3]
In [2]: mapping = {1: "one", 2: "two", 3: "three"}
In [3]: map(mapping.get, start)
Out[3]: ['one', 'two', 'three']
尝试使用map()或列表推导:
>>> org_list = ['aa', 'b2', 'c', 'd']
>>> mapping = {'aa': 1, 'b2': 2, 'd': 3, 'c': 4}
>>> map(mapping.__getitem__, org_list)
[1, 2, 4, 3]
>>> [mapping[x] for x in org_list]
[1, 2, 4, 3]
mapping = dict(zip(org_list, range(1, 5))) # change range(1, 5) to whatever
gen_list = [mapping[elem] for elem in org_list] # you want it to be