Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Merge list into sparse list efficiently

I have two lists:

a = [None, None, 1, None, 4, None, None, 5, None]
b = [7,8,2,3,6,9]

I want to merge them, either to create a new list or just update a, by filling in the Nones with the values from b, so

a = [7,8,1,2,4,3,6,5,9]

What's the most efficient way of doing this?

For extension, I'll be wanting to do this with every permutation of b. Does this allow shortcutting the technique at all?

like image 228
xorsyst Avatar asked Jun 13 '18 07:06

xorsyst


3 Answers

This is one approach. Using a list comprehension and converting b to a iterator object.

Demo:

a = [None, None, 1, None, 4, None, None, 5, None]
b = [7,8,2,3,6,9]
b = iter(b)

print( [next(b) if i is None else i for i in a] )

Output:

[7, 8, 1, 2, 4, 3, 6, 5, 9]
like image 104
Rakesh Avatar answered Nov 05 '22 17:11

Rakesh


With list.pop() method on reversed 2nd b list:

a = [None, None, 1, None, 4, None, None, 5, None]
b = [7,8,2,3,6,9]
tmp = b[::-1]

result = [tmp.pop() if i is None else i for i in a]
print(result)    # [7, 8, 1, 2, 4, 3, 6, 5, 9]
like image 3
RomanPerekhrest Avatar answered Nov 05 '22 18:11

RomanPerekhrest


for reversed_index in range(len(a) - 1, -1, -1):
    if a[reversed_index] is None:
        a[reversed_index] = b.pop()

It should be efficient as it modifies a in place and right popping a list is also efficient. As far as I think, it is an O(len(a)) solution.

like image 3
Sraw Avatar answered Nov 05 '22 17:11

Sraw