Python one liner lambda function – filter array of chars return char if it’s in another set of chars

  lambda, python

I have two arrays:

  • 1st – all the chars of a string
  • 2nd – a list of chars

I want to write a lambda function to filter the 1st array to all instances of chars that are also found in the second array (or I could use another data structure if that’s necessary).

I wrote this logic separately,

#Basic for loop doing the same logic
for val in checkArr:
    if val in extractChars:
        filtered.append(val)

and of course I could just encase it in a separate function, but I’m wondering if it’s even possible to do this sort of thing with a one-liner lambda.

In javascript it would look like this:

checkArr.filter(i => { if(extractChars.includes(i)){return i}}) 

Python:

#setup - not relevant to question
def splitChar(str):
    return [char for char in str]

str = "adsfg hdfss  h s"
checkArr = splitChar(str)
extractChars = ["s", "h", "j"]

filtered = []

#What I am trying to write but am having trouble with the syntax & possibility
filtered = list(filter(lambda i: i in extractChars) , checkArr)) 

#Basic for loop doing the same logic
for val in checkArr:
    if val in extractChars:
        filtered.append(val)

print(filtered)

Source: Python Questions

LEAVE A COMMENT