I wanted to declare an if statement inside a lambda function:
Suppose:
cells = ['Cat', 'Dog', 'Snake', 'Lion', ...]
result = filter(lambda element: if 'Cat' in element, cells)
Is it possible to filter out the 'cat' into result?
If you want to filter out all the strings that have 'cat' in them, then just use
>>> cells = ['Cat', 'Dog', 'Snake', 'Lion']
>>> filter(lambda x: not 'cat' in x.lower(), cells)
['Dog', 'Snake', 'Lion']
If you want to keep those that have 'cat' in them, just remove the not.
>>> filter(lambda x: 'cat' in x.lower(), cells)
['Cat']
You could use a list comprehension here too.
>>> [elem for elem in cells if 'cat' in elem.lower()]
['Cat']
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