Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find matching partial substring in python

Tags:

python

I want to check if any element in noun matches any one of the elements in tables.

First element in nous in "devices". Clearly it matches with "projname:dataset.devices". If a match is found, loop should break, else it should check whether second element in noun, which is "today" matches any element in the tables.

    tables = ["projname:dataset.devices","projname:dataset.attempts"]

    noun = [devices,today]

I tried it with "noun in tables", i got empty result. Is there any other method that I can try with?

Thanks in advance !!

like image 275
user3447653 Avatar asked Mar 22 '26 04:03

user3447653


2 Answers

A simple use of any(n in s for n in nouns for s in tables) would suffice for a check.

If you actually want the matching item, you could write this quick function:

>>> def first_match(nouns, tables):
...     for n in nouns:
...         for t in tables:
...             if n in t:
...                 return t
...
>>> first_match(nouns,tables)
'projname:dataset.devices'
like image 109
juanpa.arrivillaga Avatar answered Mar 23 '26 17:03

juanpa.arrivillaga


Task:

  1. 'Check if any element in noun matches any one of the elements in tables'
  2. 'If any function returns true, I have to get the corresponding element in tables'

Data:

tables = ["projname:dataset.devices","projname:dataset.attempts"]
noun = ['devices','today']

Generator expression:

This only gives the first match, as per OP request.

try:
    print(next(t for n in noun for t in tables if n in t))
except StopIteration:
    pass

Output:

   'projname:dataset.devices'
like image 29
nipy Avatar answered Mar 23 '26 18:03

nipy