1

suppose I have two string list:

a=['ab','ac','ad']
b=['abcd','baa','bacd','bbaa']

and I want to know if each element of list b has any of strings in a as its substring. The correct result should be: [True,False,True,False]. How do I code this?

2 Answers 2

1

You can use built-in function any within a list comprehension:

>>> [any(i in j for i in a) for j in b]
[True, False, True, False]
2
  • I am a pyhton n00b, can you explain this to me like I am 5
    – frank
    Commented Apr 18, 2019 at 15:38
  • @alex i in j for i in a generates a series of Boolean objects (i in j which checks if i exist in j) and any does what's explained in documentation on those objects and returns one Boolean object in result. This process repeats with for j in b.
    – Kasravnd
    Commented Apr 18, 2019 at 16:14
0

Something like:

[any([i in j for i in a]) for j in b]

would do the trick.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.