Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Search list of string elements that match another list of string elements

Tags:

python

I have a list with strings called names, I need to search each element in the names list with each element from the pattern list. Found several guides that can loop through for a individual string but not for a list of strings

a = [x for x in names if 'st' in x]

Thank you in advance!

names = ['chris', 'christopher', 'bob', 'bobby', 'kristina']
pattern = ['st', 'bb']

Desired output:

a = ['christopher', 'bobby', 'kristina]
like image 581
Christopher Avatar asked Mar 21 '16 15:03

Christopher


People also ask

How do you check if an element of a list is in another list?

There are 2 ways to understand check if the list contains elements of another list. First, use all() functions to check if a Python list contains all the elements of another list. And second, use any() function to check if the list contains any elements of another one.

How do you check if a list of string contains a string?

Using String.contains() method for each substring. You can terminate the loop on the first match of the substring, or create a utility function that returns true if the specified string contains any of the substrings from the specified list.

How do you match a string to a list in Python?

Python Find String in List using count() We can also use count() function to get the number of occurrences of a string in the list. If its output is 0, then it means that string is not present in the list. l1 = ['A', 'B', 'C', 'D', 'A', 'A', 'C'] s = 'A' count = l1.

How do I combine a list of elements in a string?

To convert a list to a string, use Python List Comprehension and the join() function. The list comprehension will traverse the elements one by one, and the join() method will concatenate the list's elements into a new string and return it as output.


2 Answers

Use the any() function with a generator expression:

a = [x for x in names if any(pat in x for pat in pattern)]

any() is a short-circuiting function, so the first time it comes across a pattern that matches, it returns True. Since I am using a generator expression instead of a list comprehension, no patterns after the first pattern that matches are even checked. That means that this is just about the fastest possible way of doing it.

like image 89
zondo Avatar answered Oct 19 '22 00:10

zondo


You can do something like this:

[name for name in names if any([p in name for p in pattern])]

The code is self explanatory, just read it out loud; we're creating a list of all names that have one of the patterns in them.

Using two loops:

for name in names:
    for pattern in patterns:
        if pattern in name:
            # append to result
like image 2
Maroun Avatar answered Oct 19 '22 01:10

Maroun