Conor
Conor

Reputation: 593

return matches if match

I'm doing some pattern matching, and want to check whether part of a string appears in a list of strings. Doing something like this:

if any(x in line for x in aListOfValues):

Is it possible to return the value of x in addition to the line?

Upvotes: 1

Views: 790

Answers (3)

miradulo
miradulo

Reputation: 29690

You could use next() to retrieve the next match from a similar generator, with a False default. Note that this only returns the first match, evidently not every match.

match = next((x for x in aListOfValues if x in line), False)

Alternatively, an extremely simple solution could be to just deconstruct your current statement into a loop and return a tuple containing x as well as the line.

def find(line, aListOfValues):
    for x in aListOfValues:
        if x in line:
            return x, line
    return False, line

Upvotes: 3

Ari Gold
Ari Gold

Reputation: 1548

aListOfValues = ["hello", "hallo"]
line = "hello world"
#classic one
res = [x for x in aListOfValues if x in line]
print res
>>['hello']

# back to your case
if any(x in line for x in aListOfValues):
  print set(aListOfValues) & set(line.split())
>> set(['hello'])

match = set(aListOfValues) & set(line.split())
if match: #replace any query
  print match
>> set(['hello'])

Upvotes: 0

Jean-François Fabre
Jean-François Fabre

Reputation: 140168

You could do it by consuming the first item returned on match using next. Note that you have to protect against StopIteration exception if you're not sure you're going to find a pattern:

try:
    print (next(x for x in aListOfValues if x in line))
except StopIteration:
    print("Not found")

Upvotes: 1

Related Questions