Search code examples
pythondictionarypython-itertools

swapping inside the list in python


Suppose that I have two lists that contain the following elements. i.e.

l1 = ['a','b','c']
l2 = [1,2,3]

each element of l1 is related to the corresponding element in l2 at the same index. The relation is such that if the user enters the list l1 the output is l2.Suppose if the user enters a list such as ['a','c','b'] then the output should be [1,3,2]. How can I do the following function ? The easier way is to use a dictionary that corresponds each element of l1 to that of l2 .But I am looking for a better method, if not then a smaller code .. Another example (Just In Case)

l1 = ['c','b','a']
l2 = [3,2,1]

Solution

  • I'm assuming you want them to line up as follows:

    a  b  c  d  e  f  g  h  i  j  k  l  ...
    1  2  3  4  5  6  7  8  9  10 11 12 ...
    

    You should define a dictionary to do this, like you said. You can either use dict(zip(...)):

    def get_nums(lst):
        letters = 'abcdefghijklmnopqrstuvwxyz' # also string.ascii_lowercase
        numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16,
                   17, 18, 19, 20, 21, 22, 23, 24, 25, 26] # range(1, 27)
        mapping = dict(zip(letters,numbers))
        return [mapping[lett] for lett in lst]
    

    Or you could just use enumerate for this

    def get_nums(lst):
        letters = 'abcdefghijklmnopqrstuvwxyz' # also string.ascii_lowercase
        mapping = {lett:idx for idx,lett in enumerate(letters, start=1)}
        return [mapping[lett] for lett in lst]
    

    As castle-bravo points out, for this naive mapping you can use something like:

    def get_nums(lst):
        return [ord(lett) - 96 for lett in lst]
    

    But this isn't very scalable to other mappings, and can cause unexpected issues if your input isn't rigorously defined.