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 ?
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)
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With