gpt4 book ai didi

根据映射从给定列表生成列表的Python程序

转载 作者:太空宇宙 更新时间:2023-11-04 06:50:44 24 4
gpt4 key购买 nike

例如

组织列表:

aa b2 c d

映射:

aa 1
b2 2
d 3
c 4

基因列表:

1 2 4 3

Python 的实现方式是什么?假设 org_list 和映射在文件 org_list.txtmapping.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

关于根据映射从给定列表生成列表的Python程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16136482/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com