Home > Software design >  Check if values from the list exist in another list without additional characters
Check if values from the list exist in another list without additional characters

Time:03-22

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)

CodePudding user response:

Perhaps you're looking for set.issubset:

for k, lst in {'a': a, 'c': c}.items():
    if set(lst).issubset(b):
        print(f'{k} is OK')
    else:
        print(f'{k} is not OK')

Output:

a is not OK
c is OK

CodePudding user response:

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

CodePudding user response:

Check if in list 'a' there is an element not present in 'b'

for x in a:
    if x not in b:
        print("Not correct")
  • Related