List returned by map function disappears after one use(map 函数返回的列表在使用一次后消失)
问题描述
我是 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.
这篇关于map 函数返回的列表在使用一次后消失的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:map 函数返回的列表在使用一次后消失
基础教程推荐
- 如何在 Python 中检测文件是否为二进制(非文本)文 2022-01-01
- 使用 Google App Engine (Python) 将文件上传到 Google Cloud Storage 2022-01-01
- 如何在Python中绘制多元函数? 2022-01-01
- 症状类型错误:无法确定关系的真值 2022-01-01
- 将 YAML 文件转换为 python dict 2022-01-01
- 哪些 Python 包提供独立的事件系统? 2022-01-01
- 使 Python 脚本在 Windows 上运行而不指定“.py";延期 2022-01-01
- 合并具有多索引的两个数据帧 2022-01-01
- 使用Python匹配Stata加权xtil命令的确定方法? 2022-01-01
- Python 的 List 是如何实现的? 2022-01-01