python - 如何使用Python 3的索引从map函数的结果中获取值?

标签 python python-3.x

我试试这个:

def test(x):
    return x**2

a = map(test,[1,2,3])

如果我得到这样的值:

for i in a:
    print(a)

我将得到 1,4,9 并且效果非常好。

但是如果我这样做:a[0]。将引发错误。

我知道这是因为map函数的结果是map类:

type(map(test,[1,2,3])) == <class 'map'>

不可订阅。

那么如何使用索引来获取map函数的结果值呢?

注意:此行为特定于 python 3。

最佳答案

map对象转换为list对象:

a = list(map(test,[1,2,3]))

然后您可以使用列表索引来访问各个元素。

关于python - 如何使用Python 3的索引从map函数的结果中获取值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37110086/

相关文章:

python - BruteForce while 循环中的计数器; yield 内存不足?

python - PyQt5 自定义 QAction 类

python-3.x - 如何使用 matplotlib 保存图像而不显示它们?

Python opencv cv2 cap.read() 在 Windows 上的 PyInstaller 中返回 None

python - JAX:避免对沿一个轴使用不同数量的元素评估的函数进行即时重新编译

python - 适用于通信进程的 Zmq 消息模式

python - 一次/并行检索多个网址

python - 有没有办法等待 os.remove() 完成?

python - 项目内的相对导入导致 "SystemError: Parent module ' '未加载,无法执行相对导入”

python - Dataframe 大型 JSON(嵌套的嵌套)