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

    enumerate函数用于遍历序列中的元素以及它们的下标,多用于在for循环中得到计数,enumerate参数为可遍历的变量,如 字符串,列表等

    一般情况下对一个列表或数组既要遍历索引又要遍历元素时,会这样写:

    1
    2
    for in range (0,len(list)): 
      print i ,list[i]

    但是这种方法有些累赘,使用内置enumerrate函数会有更加直接,优美的做法,先看看enumerate的定义:

    1
    2
    3
    4
    5
    6
    7
    def enumerate(collection): 
      'Generates an indexed series: (0,coll[0]), (1,coll[1]) ...'   
       = 0 
       it = iter(collection) 
       while 1
       yield (i, it.next()) 
       += 1

    enumerate会将数组或列表组成一个索引序列。使我们再获取索引和索引内容的时候更加方便如下:

    1
    2
    for index,text in enumerate(list)): 
      print index ,text

    代码实例1:

    1
    2
    3
    4
    5
    = 0
    seq = ['one''two''three']
    for element in seq:
        print i, seq[i]
        += 1

    0 one

    1 two

    2 three

    代码实例2:

    1
    2
    3
    seq = ['one''two''three']
    for i, element in enumerate(seq):
        print i, seq[i]

    0 one

    1 two

    2 three

    代码实例3:

    1
    2
    for i,j in enumerate('abc'):
        print i,j

    0 a

    1 b

    2 c

  • 相关阅读:
    正则匹配 sql语句参数
    正则判断是不是移动端浏览
    .net 2.0 后台多线程
    Oracle 获取当天数据
    C# 图片转Base64
    Js FileReader图片加载
    KendoUI操作笔记
    Android Studio解析Json文件内容
    LitePal
    C#最基本的小说爬虫
  • 原文地址:https://www.cnblogs.com/paranoia/p/6170791.html
Copyright © 2011-2022 走看看