McLeodx McLeodx - 5 months ago 12
Python Question

Checking if any strings in one list are a substring in another list

I know that if I just have two strings that checking using

x in y
will work. And that if I just wanted to check if a string is in any of the strings in a list I'd just use a
for
loop for that.

But what is the most pythonic/efficient way to check if any of the strings in the first list are substrings of the strings in the second list?

An example would be:

notPresent = []
present = []
listA = ['Rick', 'James']
listB = ['Rick', 'Ricky', 'Ryan', 'Jam', 'Jamesses', 'Jamboree']

notPresent = ['Ryan', 'Jam', 'Jamboree']
present = ['Rick', 'Ricky', 'Jamesses']


I'm going to use both
present
and
notPresent
words.

Answer

I would say something like this:

#python2
notPresent = set()
present = set()
listA = ['Rick', 'James']
listB = ['Rick', 'Ricky', 'Ryan', 'Jam', 'Jamesses', 'Jamboree']

#notPresent = ['Ryan','Jam','Jamboree']
#present = ['Rick','Ricky','Jamesses']

for b in listB:
  inthere = False
  for a in listA:
    if a in b:
      inthere = True
      present.add(b)
      break
  if not inthere:
    notPresent.add(b)

print(list(notPresent))
print(list(present))

So basically 2 for loops. And use sets instead of lists (fr uniqueness of values)...