Reputation: 375
I have almost completed a script to compare two lists (listA and listB). The script should return the similar values between the lists, that are following each others, and with single occurrences.
listA=['b', 'c', 'd', 'c', 'c']
listB=['a', 'b', 'c']
def ordered_matches(list1, list2):
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] and f2 != len2:
list.append(list1[f1]);
start_range = f2;
break
elif list1[f1] == list2[f2] and f2 == len2:
list.append(list1[f1]);
continue
break
return list
ordered_matches(listA, listB)
Here are examples of input/output expected:
listA=['a', 'b', 'c', 'd', 'e']
listB=['d', 'e', 'f', 'g', 'h']
output=['d','e']
listA=['a', 'b', 'c', 'd', 'e']
listB=['h', 'd', 'g', 'd', 'f']
output=['d']
listA=['b', 'a', 'c', 'a', 'e']
listB=['b', 'a', 'e', 'b', 'e']
output=['b', 'a', 'e']
To reach this result, the first for loop of the script should be broken. But unfortunately, I can't manage to break the first for loop within the second for loop.
Would you have any advice to do it?
Upvotes: 0
Views: 64
Reputation: 375
I think I have found an answer that does not require to break the outer loop. The main question of this topic is not addressed, but at least the script seems to work.
def ordered_matches(list1, list2):
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+1;
break
return list
However, it is noticeable that the position of the inputs in the command can change the outputs.
Upvotes: 1