Python 3 与 Python 2 中的映射

2022-01-10 00:00:00 python python-3.x list python-2.x iterator

问题描述

我是 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.

相关文章