0

I would like to write a python function as below:

import numpy as np
a = [[-0.17985, 0.178971],[-0.15312,0.226988]] 
(lambda x: x if x > 0 else np.exp(x)-1)(a)

Below is python error message:

TypeError                                 Traceback (most recent call last)
<ipython-input-8-78cecdd2fe9f> in <module>
----> 1 (lambda x: x if x > 0 else np.exp(x)-1)(a)

<ipython-input-8-78cecdd2fe9f> in <lambda>(x)
----> 1 (lambda x: x if x > 0 else np.exp(x)-1)(a)

TypeError: '>' not supported between instances of 'list' and 'int'

How do I fix this problem?

For example:

a = [[-0.17985, 0.178971],[-0.15312,0.226988]]

b = f(a) 

expected output

b = [[-0.1646, 0.17897],[-0.14197, 0.22699]]
2
  • '>' not supported between instances of 'list' and 'int' - nobody knows why you are comparing that (supposedly matrix) list with 0. But it is what raises the error. Commented Apr 6, 2019 at 3:02
  • Thanks to give me response. Can you guide me how to write a python function to do element-wise operation if element x > 0 return x; otherwise, take exp(x)-1 Commented Apr 6, 2019 at 4:08

1 Answer 1

1

You are having a list of lists, so an additional iteration is required:

import numpy as np

a = [[-0.17985, 0.178971],[-0.15312,0.226988]]

f = lambda x: x if x > 0 else np.exp(x)-1

res = []
for x in a:
    lst = []
    for y in x:
        lst.append(f(y))
    res.append(lst)

print(res)
# [[-0.16460448865975663, 0.17897099999999999], [-0.14197324757693675, 0.226988]]

Since end result is a list, this problem can better be solved using a list-comprehension:

[[x if x > 0 else np.exp(x)-1 for x in y] for y in a]

Or with the defined lambda:

[[f(x) for x in y] for y in a]
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.