I have the following function in Python:
def carta(lista):
a = ''
for i in lista:
if(i[:2] == 'CC') & ((i[-3:] != 'CC/')):
a = i
return a
Which returned me the value of i
if and only if some element of my list started with 'CC'
but different from 'CC/'
.
However in the production environment that I am in, functions (udf) are not allowed, so I am trying to modify that code using lambdas in the following way:
carta_lambda = lambda lista : ('CC' in lista [:2]) + lista and ('CC/' not in lista [-3:]) + lista
However this returns me a boolean mask of each element, ie a value True
or False
not i
of the list element.
As an example, if I have the following:
[CC845, RF456, BG838]
returns me aTrue
And if I have something like this:
[RF456, JP654, BG838]
returns me aFalse
However from the first list I would expect output a 'CC845'
and for the second output a 0
.
Any idea how I could implement this with lambdas?
This lambda returns an array with the elements that meet the condition:
The part
x for x in lista
loops through the entire list, but only selects items that meet the conditionif x[:2] == "CC" and x[3] != "/"
.show
produces:
carta
can also be converted to a lambda usingfilter
andnext
filter
what it does is return an iterable with the elements of another iterable that meet a condition (given by a lambda). Then withnext
takes an element from the iterable returned byfilter
. If that iterable is empty it returns by default""
.