問題描述
我是 Python 新手,正在閱讀一本 Python 舊書.它基于 Python 2,所以有時(shí)我對細(xì)節(jié)有點(diǎn)困惑.
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 中的列表,我用谷歌搜索了它,發(fā)現(xiàn) list(L
) 有效.但問題是,首先 list(L)
工作正常,但是當(dāng)我再次使用它時(shí),
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)
第二個(gè)返回[]
誰能解釋一下發(fā)生了什么?
Can somebody explain me what's happening?
推薦答案
map
返回一個(gè)迭代器.因此,它的輸出只能使用一次.如果您希望將結(jié)果存儲在列表中,與 Python 2.x 一樣,只需在使用 map
時(shí)調(diào)用 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
現(xiàn)在將包含您的結(jié)果,無論您調(diào)用它多少次.
The list L
will now contain your results however many times you call it.
您面臨的問題是,一旦 map
迭代了一次,它將不會為每個(gè)后續(xù)調(diào)用產(chǎn)生任何結(jié)果.因此,您會看到第二次調(diào)用的空列表.
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.
如果您無法用盡迭代器但希望使用兩次,有關(guān)解決方法的更詳細(xì)說明和建議,請參閱 為什么我不能在同一個(gè)數(shù)據(jù)上迭代兩次.
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.
這篇關(guān)于Python 3 與 Python 2 中的映射的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!