How can i test if multiple strings exist in another list? Below is a code example that I started with but doesn't work properly. It should return true if even part of the string is found in the list.
I marked in the comments what the result should return. as you can see they all fail though.
def all_exist(avalue, bvalue):
if avalue == []:
return True
else:
print (all(x in avalue for x in bvalue))
items = ['greg','krista','marie']
all_exist(['greg', 'krista'], items) # true
all_exist(['gre', 'kris'], items) # true
all_exist(['gre', 'purple'], items) # false
Would it be better to convert the second list to a single string and then just test if strings in list exist in it?
You have to check if all of the strings in the first list is contained by any string in the second list:
def all_exist(avalue, bvalue):
return all(any(x in y for y in bvalue) for x in avalue)
items = ['greg','krista','marie']
print(all_exist(['greg', 'krista'], items)) # -> True
print(all_exist(['gre', 'kris'], items)) # -> True
print(all_exist(['gre', 'purple'], items)) # -> False
print(all_exist([], items)) # -> True
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With