地图功能返回的列表在一次使用后消失 [英] List returned by map function disappears after one use

查看:110
本文介绍了地图功能返回的列表在一次使用后消失的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很习惯Python。我使用的是Python 3.3.2,我很难想出以下代码:

  strList = [ '1','2','3'] 
intList = map(int,strList)
最大=最大(intList)
最小=最小(intList)

给我这个错误:

 追溯(最近的呼叫最后):
文件< stdin>,第1行,< module>
ValueError:min()arg是一个空序列

但是这个代码:

  strList = ['1','2','3'] 
intList = list(map(int,strList) )
最大=最大(intList)
最小=最小(intList)

给我我没有任何错误。



我的想法是,当intList被分配给map函数的返回值时,它将成为迭代器而不是列表文档。也许作为调用 max()的副作用,迭代器已经迭代到列表的末尾,导致Python相信列表是空的(我正在绘制从C知识这里,我不知道迭代器如何真正在Python中工作。)我必须支持的唯一证据是,对于第一个代码块:

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

而对于第二个代码块:

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

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

解决方案

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


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)

Gives me this error:

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

However this code:

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

Gives me no errors at all.

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'>

whereas for the second block of code:

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

Can someone confirm or deny this for me please?

解决方案

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.

这篇关于地图功能返回的列表在一次使用后消失的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆