Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return the value of a matching item in a python list

Tags:

python

list

I have two lists myList and lookup.

myList contains the item(s) I'm searching for in lookup. The match doesn't have to be exact. But once it's found, I would like to return the value 'abc 123' from lookup. Below is my implementation. I'm stuck at the return statement.

myList = ['abc'] 
lookup = ['abc 123', 'efg 456', 'ijk 789'] 


def checkIfinLookup(mylist, lookup):
    for x in mylist:
        if any(x in s for s in lookup):
            return ? 
like image 940
Princesden Avatar asked Dec 18 '22 01:12

Princesden


2 Answers

if you want to return the string that matched the substring, you cannot use any, any won't keep the value of s when x in s.

You could use next on a search iterator, with None as default value if not found. Return from the function if not None

myList = ['abc']
lookup = ['abc 123', 'efg 456', 'ijk 789']


def checkIfinLookup(mylist, lookup):
    for x in mylist:
        n = next((s for s in lookup if x in s),None)
        if n is not None:
            return n

even better, as Stefan hinted, no need to an extra loop & test, just flatten both loops in the comprehension:

def checkIfinLookup(mylist, lookup):
    return next((s for x in mylist for s in lookup if x in s),None)
like image 128
Jean-François Fabre Avatar answered Dec 27 '22 01:12

Jean-François Fabre


I would just not use any() and list comprehension:

def checkIfinLookup(mylist, lookup):
    for x in mylist:             
        for s in lookup:                                     
            if x in s:
                return s
like image 36
AGN Gazer Avatar answered Dec 27 '22 00:12

AGN Gazer