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

时间:2013-04-21 21:37:32

标签: python

E.g。

org_list:

aa b2 c d

映射:

aa 1
b2 2
d 3
c 4

gen_list:

1 2 4 3

实现此方法的Python方法是什么?假设org_list和映射在文件org_list.txtmapping.txt中,而gen_list将写入gen_list.txt

顺便说一下,您期望哪种语言实现起来非常简单?

5 个答案:

答案 0 :(得分:5)

使用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

答案 1 :(得分:4)

这是针对您案例的解决方案。

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可以很好地处理这种情况。

答案 2 :(得分:3)

另一种方式:

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']

答案 3 :(得分:1)

尝试使用 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]

答案 4 :(得分:0)

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