0

I wish to compare lists and output the similar matches that following each other in the same order.

list1 = ['a','b', 'b', 'c']
list2 = ['b', 'a', 'a', 'c']

# With the intersection() command, the output is the matching strings regardless of the order of the strings:
set(list1).intersection(set(list2))
{'a', 'b', 'c'}

# I wish to output only the strings that are following each other in the two lists. Here the two answers could be :
{'a', 'c'}
# or
{'b', 'c'}

Would you know any tricks to do it?

1 Answers1

0

I think I have found an answer, but still have some issues with duplicated values in the lists.

list = []

len1 = len(list1) 

len2 = len(list2)

start_range = 0 for f1 in range(len1) :
    for f2 in range(start_range, len2) :
        if list1[f1] == list2[f2]:
            list.append(list1[f1]);
            start_range = f2;
            break;  
 print(list)
  • Well, unfortunately this script does not work, as it returns different values depending of the input data. Different list are printed in the output depending on the order of the input (list1 or list2) – Drosera_capensis May 09 '22 at 17:16