Search code examples
pythonlistlist-comparison

How do you find the elements in one list, in that order, in another list?


I'm trying to match all of the items in one list (list1) with some items in another list (list2).

list1 = ['r','g','g',]
list2 = ['r','g','r','g','g']

For each successive object in list1, I want to find all indices where that pattern shows up in list2:

Essentially, I'd hope the result to be something along the lines of:

"r is at indices 0,2 in list2" "r,g is at indices, 1,3 in list2" (I only want to find the last index in the pattern) "r,g,g is at index 4 in list2"

As for things I've tried: Well... a lot.

The one that has gotten closest is this:

print([x for x in list1 if x not in set(list2)])

This doesn't work fr me because it doesn't look for a group of objects, it only tests for one object in list1 being in list2.

I don't really need the answer to be pythonic or even that fast. As long as it works!

Any help is greatly appreciated! Thanks!


Solution

  • Here's an attempt:

    list1 = ['r','g','g']
    list2 = ['r','g','r','g','g']
    
    def inits(lst):
        for i in range(1, len(lst) + 1):
            yield lst[:i]
    
    def rolling_windows(lst, length):
        for i in range(len(lst) - length + 1):
            yield lst[i:i+length]
    
    for sublen, sublst in enumerate(inits(list1), start=1):
        inds = [ind for ind, roll
                in enumerate(rolling_windows(list2, sublen), start=sublen)
                if roll == sublst]
        print(f"{sublst} is in list2 at indices: {inds}")
    
    # ['r'] is in list2 at indices: [1, 3]
    # ['r', 'g'] is in list2 at indices: [2, 4]
    # ['r', 'g', 'g'] is in list2 at indices: [5]
    

    Basically, it generates relevant sublists using two functions (inits and rolling_windows) and then compare them.