python: how to get list item with the combination of first name and second name in the name list

Question:

I have a list that has names and I want to get the list element which has some part of my string

for example:

names = ["David Benj Jacob", "Alex"]

so if I search with "David Jacob" then how can I get the first element of the list "David Benj Jacob"?

I tried
if "David Jacob" in names

Asked By: levent

||

Answers:

You need to check if all parts of the substring are in any of the names

names = ["David Benj Jacob", "Alex"]
substr = "David Jacob"

valid_names = []
for name in names:
    if all(part in name for part in substr.split()):
        valid_names.append(name)
Answered By: jprebys
names = ['David benj Jacob', 'John Legend']
wanted_name = "David Jacob"
first_name, last_name = wanted_name.split(' ')
for name in names:
  if first_name in names or last_name in names:
    print(name)

or using regex and filter functions in python.
like the what the answer suggested provided here: Regular Expressions: Search in list
which would be something like:

names = ['David benj Jacob', 'John Legend']
wanted_name = "David Jacob"
first_name, last_name = wanted_name.split(' ')
pat = re.compile(fr"{first_name}.*?{last_name}")
wanted_names = list(filter(pat.match,names))
Answered By: bentrification

Try splitting the querying string to substrings and check if that substring is present in items from an names array.

names = ["David Benj Jacob", "Alex"]

def search(names: list[str], query: str) -> str:
    # Split words 
    split = query.split(" ")

    # Iterate over all names
    for item in names:
        # Iterate over all words from 'query'
        for word in split:
            # Check if word is present
            if word in item:
                return item

queried = search(names, "David Jacob")
Answered By: Zapomnij

I’ve come to a similar conclusion as @jprebys, but I’ve written a basic function that returns the index of the match in the names list given a search string.

names = ["David Benj Jacob", "Alex"]

def find_name(search: str) -> int:
    for name in names:
        if all(n in name for n in search.split()):
            return names.index(name)      
Answered By: JRiggles
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.