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]
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.
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.
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.
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.
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.
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
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