【问题标题】:Python error: 'list' object is not callable after converting the map function to listPython 错误:将映射函数转换为列表后,“列表”对象不可调用
【发布时间】:2021-11-24 05:45:54
【问题描述】:

以下代码显示我尝试映射函数列表并得到“'list'对象不可调用”的类型错误。

L1的类型是'map',所以我用list函数转换了,还是报错。

您对这个问题有任何想法吗?谢谢!

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 需要一个函数作为它的第一个参数,但 [math.sin, math.cos, math.exp] 不是一个函数,它是一个列表。你期待它做什么?
  • 这道题是用函数列表和lambda函数计算math(sin(0))、math(sin(0))、math(sin(0))。感谢您澄清这个问题。

标签: python list callable


【解决方案1】:
 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()

【讨论】:

    【解决方案2】:

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

    https://docs.python.org/3/library/functions.html#map

    但是您将列表传递给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()
    
    

    【讨论】:

    • @AmyZeng L list 是一组不同的值,还是你只想为一个值计算不同的函数?
    • 用函数列表和map函数计算[math.sin(0), math.cos(0), math.exp(0)]。分配给 sin/cos/exp 的值应该是可变的。
    • @AmyZeng,好吧,那么这个解决方案是有意义的
    【解决方案3】:

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

    import math
    func_list=[math.sin, math.cos, math.exp]
    lst = [f(0) for f in func_list]
    print(lst)
    

    【讨论】:

    • 谢谢,它很简洁,而这是一个需要在代码中包含“map”和“lambda”表达式的编码练习。
    猜你喜欢
    • 2017-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-16
    • 1970-01-01
    相关资源
    最近更新 更多