Diz*_*ral 19 python string dictionary list python-3.x
我是Python的新手.我正在使用Python 3.3.2并且我很难弄清楚为什么以下代码:
strList = ['1','2','3']
intList = map(int,strList)
largest = max(intList)
smallest = min(intList)
Run Code Online (Sandbox Code Playgroud)
给我这个错误:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: min() arg is an empty sequence
Run Code Online (Sandbox Code Playgroud)
但是这段代码:
strList = ['1','2','3']
intList = list(map(int,strList))
largest = max(intList)
smallest = min(intList)
Run Code Online (Sandbox Code Playgroud)
完全没有错误.
我的想法是,当intList被赋值给map函数的返回值时,它根据文档变成迭代器而不是列表.也许作为调用的副作用max(),迭代器已经迭代到列表的末尾,导致Python认为列表是空的(我在这里从C知识中提取,我不熟悉迭代器的真正工作方式) Python.)我必须支持的唯一证据是,对于第一个代码块:
>>> type(intList)
<class 'map'>
Run Code Online (Sandbox Code Playgroud)
而对于第二个代码块:
>>> type(intList)
<class 'list'>
Run Code Online (Sandbox Code Playgroud)
有人可以帮我确认一下吗?
use*_*ica 19
你是完全正确的.在Python 3中,map返回一个迭代器,您只能迭代一次.如果你第二次迭代一个迭代器,它会StopIteration立即升起,好像它是空的.max消耗整个事物,并将min迭代器视为空.如果需要多次使用这些元素,则需要调用list以获取列表而不是迭代器.
来自您的map文档:
返回一个迭代器,它将函数应用于每个iterable项,从而产生结果.
来自http://docs.python.org/3/library/stdtypes.html#typeiter
一旦迭代器的next()方法引发StopIteration,它必须继续在后续调用中这样做.
因此,无论基础数据对象如何,迭代器只能使用一次.它建立在发电机的概念之上.
itertools.tee 可以使用从一个多个独立的迭代器.
l1,l2 = itertools.tee(intList,2)
max(l1)
min(l2)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2911 次 |
| 最近记录: |