python-3.x - 当我尝试将地图值转换为列表以进行打印时,出现“列表”对象不可调用”错误
问题描述
我正在学习 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 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')]
推荐阅读
- php - 重用 php 和 mysql 代码,但在新项目“警告未定义数组键”中出错
- angular - 如何在 Angular Typescript 中重新加载页面以使用 BE“等待”HTTP 调用
- python - 这个错误是什么意思?以及如何解决?
- python-3.x - 无法使用 opencv 读取 .tdms 文件
- lua - 无法打开 train.lua:没有这样的文件或目录
- javascript - 无法获取未定义或空引用的属性“customXmlParts”
- javascript - 取决于所选值还显示此数组中的其他值 - javascript
- python - 为什么依赖 django 的 dropdownn 不起作用
- css - 是否有可能在 SASS 中使用 CSS 变量?
- php - 如何使新创建的类别自动设置为 wordpress 中的主要导航菜单?