John Stud
John Stud

Reputation: 1779

Compare two lists, one with a wildcard, and return a new list containing its difference

I am having difficulty figuring out how to produce this expectation given two lists, one used as a base to check against, and the other is a result list from a separate calculation.

First list:

check = ['?', 'Z']

Second list:

result = ['AZ', 'ZA', 'ZY', 'OZ']

What I have tried gets no where close but what it should do is check to see if each element in check is in result and if not, the element that fails to match in result should be swapped with the appropriate element in check.

Expectation

expectation = ['?Z', 'Z?', 'Z?', '?Z']

The example here is minimal but the problem expands to situations with more than 2 characters.

Upvotes: 0

Views: 86

Answers (1)

Frank
Frank

Reputation: 2029

Maybe there would be a more elegant solution but this should work:

check = ['?', 'Z']
result = ['AZ', 'ZA', 'ZY', 'OZ']
expectation = []  # ['?Z', 'Z?', 'Z?', '?Z']

for element in result:
    not_in_result = [char for char in check if char not in element]
    not_in_check = [char for char in element if char not in check]
    for char_not_in_result in not_in_result:
        for char_not_in_check in not_in_check:
            element = element.replace(char_not_in_check, char_not_in_result)
    expectation.append(element)

print(expectation)
# ['?Z', 'Z?', 'Z?', '?Z']

Upvotes: 1

Related Questions