zoukankan      html  css  js  c++  java
  • python3中的map对象返回的是迭代器,该迭代器用list()转列表之后,再次用list()转化时会返回空

    练习代码的时候,发现python3中的map()函数返回的可迭代对象,在用list()转成列表之后,再次用list()转列表的时候,获取的是空值(如下所示),所以查了一下python3的map()对象

    >>> rList = [1,2,3,4,5]
    >>> resultList = map(lambda x: str(x), rList)
    >>> resultList
    <map object at 0x0000021E91BFEEB8>
    >>> list(resultList)
    ['1', '2', '3', '4', '5']
    >>> list(resultList)
    []

    python3中的map方法返回的是一个迭代器:

     迭代器在遍历取值时,每取一个值时,会调用内置的__next__方法指向下一个元素:

    >>> resultList
    <map object at 0x0000021E91BFEEB8>
    >>> rList = [1,2,3,4,5]
    >>> resultList = map(lambda x: str(x), rList)
    >>> resultList.__next__
    <method-wrapper '__next__' of map object at 0x0000021E91F2A978>
    >>> resultList.__next__()
    '1'
    >>> resultList.__next__()
    '2'
    >>> resultList.__next__()
    '3'
    >>> resultList.__next__()
    '4'
    >>> resultList.__next__()
    '5'
    >>> resultList.__next__()
    Traceback (most recent call last):
    File "<stdin>", line 1, in <module>
    StopIteration
    >>> resultList.__next__()
    Traceback (most recent call last):
    File "<stdin>", line 1, in <module>
    StopIteration

    那么在用list()方法转列表的时候,每转化一个元素时都会调用一次迭代器的__next__()方法,转化完之后,__next__对象指向的就是空了,

    那么在此用list()转列表的时候,每一次用__next__()获取到的值仍然是空,所以就出现了前面的问题

  • 相关阅读:
    beta分布
    python中os.walk浏览目录和文件
    (zz)Linux下Gcc生成和使用静态库和动态库详解
    GNU scientific library
    python 字典有序无序及查找效率,hash表
    Python代码分析工具之dis模块
    python里的坑。http://www.pythoner.com/356.html
    python实现单向链表
    Python 执行字符串表达式函数(eval exec execfile)
    版本管理神器git上手
  • 原文地址:https://www.cnblogs.com/xiaxiaoxu/p/11979179.html
Copyright © 2011-2022 走看看