Home > Mobile >  Get items from list if the item contains any of the strings in another list (Python)
Get items from list if the item contains any of the strings in another list (Python)

Time:12-21

I have a list that looks like:

a_list = ['abc','acd','ade','bef','fba','adf','fac']

I would like all items in the list if it contains ab or ac. From the example above, I would like the list to be:

b_list = ['abc','acd','fac']

I have tried the following, but it gives me a TypeError.

b_list = [x for x in a_list if any(['ab','ac') in x]

CodePudding user response:

The argument to any() has to be a sequence of booleans. You just have a single boolean, and it's not the condition you want.

You want to test whether each of ab and ac is in the string, not a tuple or list of them.

b_list = [string for string in a_list if any(substring in string for substring in ('ab','ac'))]

CodePudding user response:

You're almost there but you can't cross check multiple substrings against a string. What you can do is use two conditions with an or:

b_list = [x for x in a_list if 'ab' in x or 'ac' in x]

If you have a list of substrings to check, you can use any() in your condition but you'll have to iterate over the substrings:

subs   = ('ab','ac')
b_list = [x for x in a_list if any(s in x for s in subs)]

CodePudding user response:

You almost got it. You need to iterate over ['ab','ac'] to check if it any of this exists in an item in a_list.

b_list = [item for item in a_list if any(x in item for x in ['ab','ac'])]
  • Related