首页 > 解决方案 > 当我尝试将地图值转换为列表以进行打印时,出现“列表”对象不可调用”错误

问题描述

我正在学习 map() 函数,一些教程网站使用 map() 和列表,如代码所示。他们运行代码但没有错误,但我尝试运行此代码时出现错误。你能解释一下为什么吗?

list_a = [1,2,3]
list_b = ['one', 'two', 'three']
map_func = map(list_a, list_b)
map_func = list(map_func)
print(map_func)
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-23-6ce25d7a149a> in <module>
      2 list_b = ['one', 'two', 'three']
      3 map_func = map(list_a, list_b)
----> 4 map_func = list(map_func)
      5 print(map_func)

TypeError: 'list' object is not callable

标签: python-3.xlistmapping

解决方案


Python map() 函数map() 函数在将给定函数应用于给定迭代(列表、元组等)的每个项目后返回结果列表

句法 : map(fun, iter)

返回一个迭代器,它将函数应用于可迭代的每个项目,产生结果。如果传递了额外的可迭代参数,则函数必须接受那么多参数并并行应用于所有可迭代的项目。...

例子:

# Return double of n
def addition(n):
    return n + n

# We double all numbers using map()
numbers = (1, 2, 3, 4)
result = map(addition, numbers)
print(list(result))

输出:

[2, 4, 6, 8]

你对函数的使用map()是错误的,你可能在想zip()函数

list_a = [1,2,3]
list_b = ['one', 'two', 'three']
map_func = zip(list_a, list_b)
map_func = list(map_func)
print(map_func)

输出:

[(1, 'one'), (2, 'two'), (3, 'three')]

推荐阅读