map 函数返回的列表在使用一次后消失

2022-01-31 00:00:00 python python-3.x list dictionary string

问题描述

我是 Python 新手.我正在使用 Python 3.3.2,我很难弄清楚为什么会出现以下代码:

I'm new to Python. I'm using Python 3.3.2 and I'm having a hard time figuring out why the following code:

strList = ['1','2','3']
intList = map(int,strList)
largest = max(intList)
smallest = min(intList)

给我这个错误:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: min() arg is an empty sequence

但是这段代码:

strList = ['1','2','3']
intList = list(map(int,strList))
largest = max(intList)
smallest = min(intList)

完全没有错误.

我的想法是,当 intList 被分配给 map 函数的返回值时,它变成了一个迭代器而不是一个列表,根据 文档.并且可能作为调用max()的副作用,迭代器已经迭代到列表的末尾,导致Python认为列表是空的(我这里借鉴C知识,我我不熟悉迭代器在 Python 中是如何真正工作的.)我必须支持这一点的唯一证据是,对于第一个代码块:

My thought is that when intList is assigned to the return value of the map function, it becomes an iterator rather than a list, as per the docs. And perhaps as a side effect of calling max(), the iterator has been iterated to the end of the list, causing Python to believe the list is empty (I'm drawing from C knowledge here, I'm not familiar with how iterators truly work in Python.) The only evidence I have to support this is that, for the first block of code:

>>> type(intList)
<class 'map'>

而对于第二个代码块:

>>> type(intList)
<class 'list'>

有人可以帮我确认或否认吗?

Can someone confirm or deny this for me please?


解决方案

你完全正确.在 Python 3 中,map 返回一个迭代器,您只能迭代一次.如果你第二次迭代一个迭代器,它会立即引发 StopIteration ,就好像它是空的一样.max 消耗整个事物,而 min 将迭代器视为空.如果需要多次使用元素,则需要调用 list 来获取列表而不是迭代器.

You are exactly correct. In Python 3, map returns an iterator, which you can only iterate over once. If you iterate over an iterator a second time, it will raise StopIteration immediately, as though it were empty. max consumes the whole thing, and min sees the iterator as empty. If you need to use the elements more than once, you need to call list to get a list instead of an iterator.

相关文章