map in Python 3 vs Python 2(Python 3 与 Python 2 中的映射)
问题描述
我是 Python 新手,正在阅读一本 Python 旧书.它基于 Python 2,所以有时我对细节有点困惑.
I'm a Python newbie reading an old Python book. It's based on Python 2, so sometimes I got little confused about detail.
有代码
L=map(lambda x:2**x, range(7))
所以它不会返回 python 3 中的列表,我用谷歌搜索了它,发现 list(L
) 有效.但问题是,首先 list(L)
工作正常,但是当我再次使用它时,
so it doesn't return the list in python 3, and I googled it and found that list(L
) works.
But the problem is, first list(L)
works fine,
but when I use it again,
list(L)
list(L)
第二个返回[]
谁能解释一下发生了什么?
Can somebody explain me what's happening?
推荐答案
map
返回一个迭代器.因此,它的输出只能使用一次.如果您希望将结果存储在列表中,与 Python 2.x 一样,只需在使用 map
时调用 list
:
map
returns an iterator. As such, its output may only be used once. If you wish to store your results in a list, in the same way as Python 2.x, simply call list
when you use map
:
L = list(map(lambda x:2**x, range(7)))
列表 L
现在将包含您的结果,无论您调用它多少次.
The list L
will now contain your results however many times you call it.
您面临的问题是,一旦 map
迭代了一次,它将不会为每个后续调用产生任何结果.因此,您会看到第二次调用的空列表.
The problem you are facing is that once map
has iterated once, it will yield nothing for each subsequent call. Hence you see an empty list for the second call.
如果您无法用尽迭代器但希望使用两次,有关解决方法的更详细说明和建议,请参阅 为什么我不能在同一个数据上迭代两次.
For a more detailed explanation and advice on workarounds if you cannot exhaust your iterator but wish to use it twice, see Why can't I iterate twice over the same data.
这篇关于Python 3 与 Python 2 中的映射的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Python 3 与 Python 2 中的映射


基础教程推荐
- 将 YAML 文件转换为 python dict 2022-01-01
- 如何在 Python 中检测文件是否为二进制(非文本)文 2022-01-01
- 哪些 Python 包提供独立的事件系统? 2022-01-01
- Python 的 List 是如何实现的? 2022-01-01
- 症状类型错误:无法确定关系的真值 2022-01-01
- 使用Python匹配Stata加权xtil命令的确定方法? 2022-01-01
- 合并具有多索引的两个数据帧 2022-01-01
- 使 Python 脚本在 Windows 上运行而不指定“.py";延期 2022-01-01
- 如何在Python中绘制多元函数? 2022-01-01
- 使用 Google App Engine (Python) 将文件上传到 Google Cloud Storage 2022-01-01