3

I need to enter the values of a smaller list at appropriate locations in a larger list, e.g.,

l_1 = ['a', 'c', 'e', 'd']
v_1 = [5, 6, 8, 10]

l_2 = ['a', 'ab', 'c', 'd', 'e']

I am looking to generate a v_2 of values (initialized as zeros of size l_2) which takes v_1 at locations where l_1 belongs to l_2. So, for the above example, I would like to get

v_2 = [5, 0, 6, 10, 8]

Clearly, l_1 is a subset of l_2, i.e., l_2 will always have the quantities of l_1.

I found the first answer here helpful to determine the location of l_1 in l_2 and am looking to modify it to suit my case. Ideally, I would like to have 3 inputs

a = l_1
b = l_2 
val = v_1

def ismember(a, b, val):
    bind = {}
    for i, elt in enumerate(b):
        if elt not in bind:
            bind[elt] = i
    return [bind.get(itm, None) for itm in a] 

And I need to get the return statement modified so that appropriate entries of v_1 are entered into the padded v_2, which, can be initialized as np.zeros((len(b),1)) within the function

martineau
  • 119,623
  • 25
  • 170
  • 301

1 Answers1

2

It is much easier to construct a dict for lookups using the values from l_1 as keys and v_1 as values. For example:

>>> l_1 = ['a', 'c', 'e', 'd']
>>> v_1 = [5, 6, 8, 10]
>>> l_2 = ['a', 'ab', 'c', 'd', 'e']

then

>>> d = dict(zip(l_1, v_1))
>>> [d.get(i, 0) for i in l_2]
[5, 0, 6, 10, 8]
Selcuk
  • 57,004
  • 12
  • 102
  • 110