[英]python user-defined function need help to fix error
I would like to write a python function as below: 我想写一个python函数如下:
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: 下面是python错误消息:
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]]
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
: 或者使用定义的
lambda
:
[[f(x) for x in y] for y in a]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.