Search code examples
pythonlist-comprehensiondata-munging

Python program that generate a list from a given list according to a mapping


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?


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