1

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?

Conor
  • 535
  • 2
  • 8
  • 16
  • Possible duplicate of [What is the best way to get the first item from an iterable matching a condition?](http://stackoverflow.com/questions/2361426/what-is-the-best-way-to-get-the-first-item-from-an-iterable-matching-a-condition) – Chris_Rands Feb 07 '17 at 13:48

3 Answers3

3

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
miradulo
  • 28,857
  • 6
  • 80
  • 93
  • 1
    I would also add that `next` **only** returns the first item for which the condition is True and not all in case of multiple. at least not in the way it is used here. – Ma0 Feb 07 '17 at 13:43
  • @Ev.Kounis I sort of interpreted that from the OP's question, but sure, I made that more clear. – miradulo Feb 07 '17 at 13:45
  • 1
    Thanks, stuck with your "match" solution. – Conor Feb 07 '17 at 15:04
1

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")
Jean-François Fabre
  • 137,073
  • 23
  • 153
  • 219
0
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'])
Ari Gold
  • 1,528
  • 11
  • 18