Question

E.g.

org_list :

aa b2 c d

mapping :

aa 1
b2 2
d 3
c 4

gen_list:

1 2 4 3

What is the Python way to implement this? Suppose org_list and the mapping are in files org_list.txt and mapping.txt, while the gen_list will be written into gen_list.txt

Btw, which language do you expect is very simple to implement this?

Was it helpful?

Solution

Just loop through the list with a list comprehension:

gen_list = [mapping[i] for i in org_list]

Demo:

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

If you have this data in files, first build the mapping in memory:

with open('mapping.txt') as mapfile:
    mapping = {}
    for line in mapfile:
        if line.strip():
            key, value = line.split(None, 1)
            mapping[key] = value

then build your output file from the input file:

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

OTHER TIPS

Here's a solution for your case.

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))

I think Python handles this situation gracefully enough.

Another way:

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

Try using map() or a list comprehension:

>>> 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
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top