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

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

问题描述

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

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

给我这个错误:

回溯(最近一次调用最后一次):文件<stdin>",第 1 行,在 <module> 中ValueError: min() arg 是一个空序列

但是这段代码:

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

根本没有给我任何错误.

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

<预><代码>>>>类型(整数列表)<类'地图'>

而对于第二个代码块:

<预><代码>>>>类型(整数列表)<类'列表'>

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

解决方案

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

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.

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

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