python - 为什么对map对象进行列表解析会返回空列表
阿神
阿神 2017-04-17 15:14:08
[Python讨论组]

代码出自Learning python P514,

# return a generator
def myzip(*args):
    iters = map(iter, args)              # return a list in python2.6
    while iters:                         # return a map in python3.0
        res = [next(i) for i in iters]
        yield tuple(res)

在python2.6中, map返回的是一个list, 因此可以通过next(i)遍历iters,
当iters遍历结束时, 触发StopIteration异常, while循环退出, 程序不会无限执行.

在python3.0中, map返回的是一个map对象, 结果就完全不同了, 且while会变成死循环.

In [17]: iters=map(iter,([1,2],[3,4]))

In [18]: iters
Out[18]: <map at 0x7f96a56e7c50>

In [19]: res=[next(i) for i in iters];res
Out[19]: [1, 3]

In [20]: res=[next(i) for i in iters];res
Out[20]: []

In [21]: res=[next(i) for i in iters];res
Out[21]: []

请问为什么在python 3.0中对map对象进行列表解析, 后续返回的都是 []?

阿神
阿神

闭关修行中......

全部回复(4)
高洛峰

@JackyXiong 引用的内容是对的。
在python3中,map返回了map object。在
res=[next(i) for i in iters]

对于map对象,map对象被迭代的时候,每一次会返回一个迭代器。迭代了一遍之后,就是空的了。
next(i)迭代了每一次返回的迭代器,之后,并不会将迭代后的状态再存到map对象里面。
对于list,list内的元素是可变的,你迭代了list中的每一个迭代器各一次之后,迭代后的状态还会保存在list里面。直到StopIteration
@JackyXiong 提到的,执行list(iters),可以先将map对象转化成list。这时候效果就跟python2里面的一样了。

我的猜测出于对函数式编程的考虑,将map对象设计成不变的(?)。
如果我有什么说错的地方希望指出来:)

阿神

map object 其实就是一个generator。

天蓬老师

map() and filter() return iterators. If you really need a list and the input sequences are all of equal length, a quick fix is to wrap map() in list(), e.g. list(map(...)), but a better fix is often to use a list comprehension (especially when the original code uses lambda), or rewriting the code so it doesn’t need a list at all. Particularly tricky is map() invoked for the side effects of the function; the correct transformation is to use a regular for loop (since creating a list would just be wasteful).

https://docs.python.org/3/whatsnew/3.0.html#views-and-iterators-instea...

怪我咯

@jiewhen 的答案已经很好了,我稍微补充一些。

对于map对象,map对象被迭代的时候,每一次会返回一个迭代器。迭代了一遍之后,就是空的了。

也就是map对象是一次性的,对于python2和python3,map的特性是不一样的。

python2里的对象,使用之后依然还是原来的样子,而python3迭代之后,就是空的了。


解决方法也很简单,直接在

iters=list(map(iter,([1,2],[3,4])))

添加一个list(),将格式进行转化就可以了。

我在处理自然语言文字的时候也遇到了这个问题,https://feiyang.li/2017/02/15... 也许对你会有所帮助。

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号