Home > Enterprise >  Fastest way to add special character at multiple indices using values from another list
Fastest way to add special character at multiple indices using values from another list

Time:05-05

I have 2 lists.

l1 = [1,3,6]
l2 = [10,20,30,30,40]

I need a faster way to build a list as follows:

l3 = [10,!,20,!,30,30,!,40]

I have tried the insert() at index function but that does solve the problem when the list size is big.

CodePudding user response:

Using NumPy may result in a faster code. It can be evaluated after OP put his examined code:

l1 = np.array(l1, dtype=np.int64)
l2 = np.array(l2)

result_shape = l1.shape[0] l2.shape[0]              # 8
result = np.zeros(result_shape, dtype=object)       # [0 0 0 0 0 0 0 0]
ind = np.delete(np.arange(result_shape), l1)        # [0 2 4 5 7]

result[l1] = "!"                                    # [0 '!' 0 '!' 0 0 '!' 0]
result[ind] = l2                                    # [10 '!' 20 '!' 30 30 '!' 40]

or in a smaller form without converting l1 and l2 in NumPy:

result_shape = len(l1) len(l2)                      # 8
result = np.zeros(result_shape, dtype=object)       # [0 0 0 0 0 0 0 0]
ind = np.delete(np.arange(result_shape), l1)        # [0 2 4 5 7]

result[l1] = "!"                                    # [0 '!' 0 '!' 0 0 '!' 0]
result[ind] = l2                                    # [10 '!' 20 '!' 30 30 '!' 40]   

and with loops (loops will be faster than NumPy in small lists):

i = 0
j = l1[i]
for l in range(len(l1) len(l2)):
    if l == j:
        l2.insert(j, "!")
        if i < len(l1) - 1:
            i  = 1
            j = l1[i]
  • Related