zoukankan      html  css  js  c++  java
  • python enumerate 用法

    enumerate(sequencestart=0)

    Return an enumerate object. sequence 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 sequence:

    >>>
    >>> seasons = ['Spring', 'Summer', 'Fall', 'Winter']
    >>> list(enumerate(seasons))
    [(0, 'Spring'), (1, 'Summer'), (2, 'Fall'), (3, 'Winter')]
    >>> list(enumerate(seasons, start=1))
    [(1, 'Spring'), (2, 'Summer'), (3, 'Fall'), (4, 'Winter')]
    

    Equivalent to:

    def enumerate(sequence, start=0):
        n = start
        for elem in sequence:
            yield n, elem
            n += 1
    

    New in version 2.3.

    Changed in version 2.6: The start parameter was added.

    enumerate用法另一篇文章

    参数为可遍历的变量,如 字符串,列表等; 返回值为enumerate类:

    import string
    s = string.ascii_lowercase
    e = enumerate(s)
    print s
    print list(e)

    输出为:

    abcdefghij
    [(0, 'a'), (1, 'b'), (2, 'c'), (3, 'd'), (4, 'e'), (5, 'f'), (6, 'g'), (7, 'h'), (8, 'i'), (9, 'j')]

    在同时需要index和value值的时候可以使用 enumerate。

    enumerate 实战

    line 是个 string 包含 0 和 1,要把1都找出来:

    #方法一
    def read_line(line):
        sample = {}
        n = len(line)
        for i in range(n):
            if line[i]!='0':
                sample[i] = int(line[i])
        return sample
     
    #方法二
    def xread_line(line):
        return((idx,int(val)) for idx, val in enumerate(line) if val != '0')
     
    print read_line('0001110101')
    print list(xread_line('0001110101'))
  • 相关阅读:
    poj 3253超时
    poj 3617输出格式问题
    dfs的返回条件
    hdu1010感想
    2018.7.19训练赛总结
    2018.7.12训练赛 -G
    汇编实验16 编写包含多个功能子程序的中断例程——浅谈直接地址表
    新的一年来了,先看一看自己的编程能力吧!
    汇编实验15:安装新的int 9中断例程
    汇编实验14:访问CMOS RAM
  • 原文地址:https://www.cnblogs.com/youxin/p/3060513.html
Copyright © 2011-2022 走看看