zoukankan      html  css  js  c++  java
  • 内置函数enumerate()

    enumerate是枚举的意思,顾名思义,enumerate()函数用来将一个可迭代序列生成一个enumerate对象,该enumerate对象的每个元素是由可迭代对象的索引编号和对应的元素组成的元祖。

    看看官方说明:

    Return an enumerate object. iterable must be a sequence, an iterator, or some other object which supports iteration. The __next__() method of the iterator returned by enumerate() returns a tuple containing a count (from start which defaults to 0) and the values obtained from iterating over iterable.
    

    用法:

    enumerate(iterable, start=0)
    

    看看示例一下就明白了:

    >>> s='hello'
    >>> enumerate(s)
    <enumerate object at 0x00000000027CC990>
    
    >>> e=enumerate(s)
    >>> type(e)
    <class 'enumerate'>
    
    >>> for i in e:
    ... 	print(i)
    ... 
    (0, 'h')
    (1, 'e')
    (2, 'l')
    (3, 'l')
    (4, 'o')
    

    当需要遍历一个对象并为每个元素指定一个编号时,用enumerate生成元祖序列然后解包遍历一下就实现了。

    默认的,索引编号从0开始,但是多数时候你可能想要从1开始。enumerate函数提供了可选参数,用start就可以指定开始编号了。

    >>> e=(enumerate(s,start=1))
    >>> for i in e:
    ...     print(i)
    ...
    (1, 'h')
    (2, 'e')
    (3, 'l')
    (4, 'l')
    (5, 'o')
    

    参考:https://docs.python.org/3/library/functions.html#enumerate

  • 相关阅读:
    Python-Matplotlib 12 多图figure
    Python-Matplotlib 11 子图-subplot
    Python Day16
    Python Day15
    Python Day13-14
    Python Day12
    Python Day11
    Python Day9-10
    Python Day8
    Python Day8
  • 原文地址:https://www.cnblogs.com/keithtt/p/7639051.html
Copyright © 2011-2022 走看看