Skip to content
Advertisement

Check if values from the list exist in another list without additional characters

I have 2 lists:

a = ["ad", "news", "something else", "another something"]
c = ["coupon", "ad"]

List a (and c ) must contain only characters from list b. Also in the list a(and c ) can be missed characters from list b but the characters from the list be must appear or partially :

b = ["coupon", "ad", "news"]

As a result, list a (because it contains additional characters) is wrong and list c is OK (although- it doesn’t have “news”).

I started writing nested if and I am stuck

for x in ["coupon", "ad", "news"]:
    for z in ["ad", "news", "something else", "another something"]:
        print(x,z)

Advertisement

Answer

I have defined 2 functions.

The first one will take in 2 lists of strings, and return if any of the strings in the first list exists in the second list:

def validate(lst1, lst2):
    return all(i in lst2 for i in lst1)

a = ["ad", "news", "something else", "another something"]
c = ["coupon", "ad"]

b = ["coupon", "ad", "news"]

print(validate(a, b))
print(validate(c, b))

Output:

False
True

The second one checks if all the characters used the each string in the first list exists in any of the strings in the second list:

def validate(lst1, lst2):
    characters = ''.join(lst2)
    return all(j in characters for i in lst1 for j in i)

a = ["ad", "news", "something else", "another something"]
c = ["coupon", "ad"]

b = ["coupon", "ad", "news"]

print(validate(a, b))
print(validate(c, b))

Output:

False
True
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement