zoukankan      html  css  js  c++  java
  • Python中enumerate用法详解

    enumerate()是python的内置函数、适用于python2.x和python3.x
    enumerate在字典上是枚举、列举的意思
    enumerate参数为可遍历/可迭代的对象(如列表、字符串)
    enumerate多用于在for循环中得到计数,利用它可以同时获得索引和值,即需要index和value值的时候可以使用enumerate
    enumerate()返回的是一个enumerate对象

    >>> lst = [1, 2, 3, 4, 10, 5]
    >>> enumerate(lst)
    <enumerate object at 0x00000000032A3990>

    描述

    enumerate() 函数用于将一个可遍历的数据对象(如列表、元组或字符串)组合为一个索引序列,同时列出数据和数据下标,一般用在 for 循环当中。

    Python 2.3. 以上版本可用,2.6 添加 start 参数。

    语法

    以下是 enumerate() 方法的语法:

    enumerate(sequence, [start=0])

    参数

    • sequence -- 一个序列、迭代器或其他支持迭代对象。
    • start -- 下标起始位置。

    返回值

    返回 enumerate(枚举) 对象。

    实例

    以下展示了使用 enumerate() 方法的实例:

    >>>seasons = ['Spring', 'Summer', 'Fall', 'Winter']
    >>> list(enumerate(seasons))
    [(0, 'Spring'), (1, 'Summer'), (2, 'Fall'), (3, 'Winter')]
    >>> list(enumerate(seasons, start=1))       # 下标从 1 开始
    [(1, 'Spring'), (2, 'Summer'), (3, 'Fall'), (4, 'Winter')]

    普通的 for 循环

    >>>i = 0
    >>> seq = ['one', 'two', 'three']
    >>> for element in seq:
    ...     print i, seq[i]
    ...     i +=1
    ... 
    0 one
    1 two
    2 three

    for 循环使用 enumerate

    >>>seq = ['one', 'two', 'three']
    >>> for i, element in enumerate(seq):
    ...     print i, element
    ... 
    0 one
    1 two
    2 three
  • 相关阅读:
    排序前后console.log输出无变化
    Cause: java.sql.SQLException: ORA-00904: "ID": 标识符无效
    无法解析Model中的实体类
    generatorConfig.xml
    cannot load oci dll [87/193]:
    jsp页面在 移动端 自适应,chrome浏览器没问题,可是safari浏览器有问题的解决方法
    【DP专题】——洛谷P1220关路灯
    学习笔记:查最大内存
    c++ try throw catch
    Dijkstra算法
  • 原文地址:https://www.cnblogs.com/hanfe1/p/10594495.html
Copyright © 2011-2022 走看看