pythonlistmerge

What is the best way to merge two lists by markers inside them?


For example, I have two lists:

list1 = ['x', 'x', 'o', 'o', 'x', 'x']
list2 = ['o', 'x', 'o']

I'd like to merge them in a way, that they're aligned by some markers (here it is o), so I'd like to get:

list3 = ['x', 'x', 'o', 'x', 'o', 'x', 'x']

I have only 'x' and 'o' symbols. Two lists ALWAYS have at least one marker, the order of merging two lists does not matter. For instance:

list1 = ['x', 'x', 'o', 'o', 'x', 'x']
list2 = ['x', 'x', 'x', 'o', 'x', 'o']
list3 = ['x', 'x', 'x', 'o', 'x', 'o', 'x', 'x']

What is the best pythonic way to implement it?


Solution

  • def merge_lists_by_markers(list1, list2):
        
        l1 = "".join(list1).split("o")
        l2 = "".join(list2).split("o")
        
        l3 = []
        for sublist1, sublist2 in zip(l1, l2):
            if len(sublist1) > len(sublist2):
                l3.append(sublist1)
            else:
                l3.append(sublist2)
                
        return list("o".join(l3))
    
    list1 = ['x', 'x', 'o', 'o', 'x', 'x']
    list2 = ['o', 'x', 'o']
    list3 = merge_lists_by_markers(list1, list2)
    print(list3)
    
    list1 = ['x', 'x', 'o', 'o', 'x', 'x']
    list2 = ['x', 'x', 'x', 'o', 'x', 'o']
    list3 = merge_lists_by_markers(list1, list2)
    print(list3)
    

    Output:

    ['x', 'x', 'o', 'x', 'o', 'x', 'x']
    ['x', 'x', 'x', 'o', 'x', 'o', 'x', 'x']