Python 错误:"列表"对象在将映射函数转换为列表后不可调用



下面的代码显示我试图映射一个函数列表,并得到一个类型错误' 'list'对象是不可调用的' '。

L1的类型是'map',所以我使用列表函数来转换它,它仍然返回一个错误。

你对这个问题有什么想法吗?谢谢!
import math
func_list=[math.sin, math.cos, math.exp]
result=lambda L: map(func_list, L)
L=[0,0,0]
L1=result(L)
for x in L1:
print(x)

结果类型为<class 'function'>结果类型为<class 'map'>

Traceback (most recent call last) 
<ipython-input-22-17579bed9240> in <module>
6 print("the type of result is " + str(type(result)))
7 print("the type of result is " + str(type(L1)))
----> 8 for x in L1:
9     print(x)

TypeError: 'list' object is not callable

请阅读map(function, iterable)函数的文档:

https://docs.python.org/3/library/functions.html地图但是你把list传递给function参数。

所以你的例子可以被替换为下一个代码,例如:

import math
func_list = [math.sin, math.cos, math.exp]
result=lambda L: map(lambda x: map(lambda func: func(x), func_list), L)
L = [0, 0, 0]
L1 = result(L)
for x in L1:
for value in x:
print(value, end=' ')

print()

下面似乎是获得相同结果的更短的方法。

import math
func_list=[math.sin, math.cos, math.exp]
lst = [f(0) for f in func_list]
print(lst)
import math
func_list = [math.sin, math.cos, math.exp]
result=lambda L: map(lambda x: map(lambda func: func(x), func_list), L)
L = [0, 0, 0]
L1 = result(L)
for x in L1:
for value in x:
print(value, end=' ')
print()

最新更新