user3447653
user3447653

Reputation: 4148

Find matching partial substring in 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 !!

Upvotes: 3

Views: 327

Answers (5)

nipy
nipy

Reputation: 5488

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'

Upvotes: 1

GantTheWanderer
GantTheWanderer

Reputation: 1292

Note that in your code, when you say noun in tables it means is a list (noun) INSIDE of another list (tables). Thats not what we want to find out, rather you want to find each noun that exists inside of one of the elements of tables. Try the following:

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

nouns = ["devices","today"]

for noun in nouns:
    for table in tables:
        if noun in table:
            print "Found", noun
            break

Upvotes: 0

Iron Fist
Iron Fist

Reputation: 10951

How about this simple solution:

>>> tables = ["projname:dataset.devices","projname:dataset.attempts"]
>>> noun = ['devices','today']
>>> for x in noun:
        if any(x in s for s in tables):
            print('Found !')
            break


Found !

Upvotes: 0

Liron Lavi
Liron Lavi

Reputation: 431

By your comment I assume the elements in the list aren't strings, I don't know any way of getting the var name on python, so this is my solution

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

noun = {"devices": devices, "today": today}

for n in noun:
    for table in tables:
        if n in table:
            break

Upvotes: 0

juanpa.arrivillaga
juanpa.arrivillaga

Reputation: 95948

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'

Upvotes: 3

Related Questions