Home > database >  Merging 2 list elementwise vertically python
Merging 2 list elementwise vertically python

Time:07-20

I have 2 lists:

a=[1,2,3,4]
b=[5,6]

I want to merge to make list c such that final answer is

c=[1,5,2,6,3,4]

I don't want to use any built-in modules I tried zip but it stops at shorter list

CodePudding user response:

Use more_itertools.roundrobin:

# pip install more-itertools
from more_itertools import roundrobin

c = list(roundrobin(a,b))

output: [1, 5, 2, 6, 3, 4]

without installing more-itertools, you can also use the itertools recipe:

from itertools import cycle, islice
def roundrobin(*iterables):
    "roundrobin('ABC', 'D', 'EF') --> A D E B F C"
    # Recipe credited to George Sakkis
    num_active = len(iterables)
    nexts = cycle(iter(it).__next__ for it in iterables)
    while num_active:
        try:
            for next in nexts:
                yield next()
        except StopIteration:
            # Remove the iterator we just exhausted from the cycle.
            num_active -= 1
            nexts = cycle(islice(nexts, num_active))

CodePudding user response:

Without using any builtin modules, this is probably the simplest — zip what is zippable, concatenate the rest:

s = min(len(a), len(b))
result = [e for pair in zip(a, b) for e in pair]   a[s:]   b[s:]

CodePudding user response:

Here's one way without any built-in modules:

def merge(a, b):
  shorter_list = b if len(a) > len(b) else a
  longer_list = a if len(a) > len(b) else b
  return sum(zip(a, b), ())   longer_list[len(shorter_list):]

CodePudding user response:

using loops only

a=[1,2,3,4]
b=[5,6]
 
i = 0
j = 0
 
result =[]
while i<len(a) or j <len(b):
    if i <len(a):
        result.append(a[i])
        i =1
    if j < len(b):
        result.append(b[j])
        j =1
 
print(result) # [1,5,2,6,3,4]
  • Related