【问题标题】:I need help converting map() into a list() in Python [closed]我需要帮助在 Python 中将 map() 转换为 list() [关闭]
【发布时间】:2020-09-13 20:34:05
【问题描述】:

我是 python 新手,正在为类做作业,尝试将包含先前 lambda 函数的映射转换为列表后出现错误。

我写的代码如下:

converter = lambda x: x*2 if isinstance(x, int) else x

print(list(map(converter, list_example)))

我收到的错误是:

TypeError: 'list' object is not callable

list_example 是我之前创建的列表。

感谢您的帮助!

【问题讨论】:

  • 你遇到了什么错误?
  • 抱歉没有澄清:TypeError: 'list' object is not callable
  • 那是因为您使用list 作为列表名称的变量。所以它不再是list 函数。
  • 不要使用标准 Python 关键字作为变量名。不要命名任何东西liststrdict
  • 非常感谢!!这就是发生的事情

标签: python list typeerror


【解决方案1】:

这对我来说很好用:

>>> list_example = [1, 2, 3, 4]
>>> converter = lambda x: x*2 if isinstance(x, int) else x
>>>
>>> print(list(map(converter, list_example)))
[2, 4, 6, 8]

您的错误可能是您之前重新定义了内置 list 函数以引用其他内容。永远不要这样做:

list = [1, 2, 3]  # NO!  BAD!

如果您在代码前面的某处有这样的一行,请选择一个不同的名称,您以后使用 list 函数现在应该可以工作了。

【讨论】:

    猜你喜欢
    • 2022-01-05
    • 2011-07-09
    • 1970-01-01
    • 1970-01-01
    • 2016-04-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-05
    相关资源
    最近更新 更多