ERJAN
ERJAN

Reputation: 24500

How do I convert complex function to lambda in python?

I'm thinking of ways to convert a more complex function to lambda and put it inside a map instead of f. The function is this:

#this function should be in lambda
def f(s):
    if (type(s) == int):
        return s*2
    else:
        return s.replace('r', '*')

lst = [4,5,6,'rer', 'tr',50,60]
lst = list(map( f, lst))
#result of lst is [8, 10, 12, '*e*', 't*', 100, 120]
#lst = list(map ( lambda x.... , lst))

Or lambda is only supposed to deal with short functions? Big ones have to be 'decomposed' out into separate functions?

Upvotes: 0

Views: 540

Answers (2)

meW
meW

Reputation: 3967

Prefer isinstance in place of type

lst = [4,5,6,'rer', 'tr',50,60]
lst = list(map(lambda x: x*2 if isinstance(x, int) else x.replace('r', '*'), lst))

lst
[8, 10, 12, '*e*', 't*', 100, 120]

Upvotes: 1

U13-Forward
U13-Forward

Reputation: 71580

Use if else statement in a lambda:

print(list(map(lambda x: x*2 if type(x)==int else x.replace('r','*'),lst)))

Output:

[8, 10, 12, '*e*', 't*', 100, 120]

Even better, use isinstance:

print(list(map(lambda x: x*2 if isinstance(x,int) else x.replace('r','*'),lst)))

Upvotes: 2

Related Questions