• Python 列表推导、迭代器与生成器


    1、列表推导

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    numbers = [i for i in range(10) if i % 2 == 0]
    print(numbers)
     
    seq = ["one", "two", "three"]
    for i, element in enumerate(seq):
        print(i, element)
     
    def treatment(pos, element):
        return ('%d: %s' % (pos, element))
     
    print ([treatment(i, element) for i, element in enumerate(seq)])
    1
    2
    3
    4
    5
    6
    enumerate(sequence, [start=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 corresponding value obtained from iterating over iterable.
    enumerate() is useful for obtaining an indexed series: (0, seq[0]), (1, seq[1]), (2,seq[2]), ....

    2、迭代器

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    class MyIterator(object):
        def __init__(self, step):
            self.step = step
        def __next__(self): # 3.0之后一般采用该样式
            if self.step == 0:
                raise StopIteration
            self.step -= 1
            return self.step
        def __iter__(self):
            return self
     
    for i in MyIterator(5):
        print(i)

    3、生成器

    1
    2
    3
    4
    5
    6
    7
    8
    9
    def fibonacci():
        a, b = 0, 1
        while True:
            yield b
            a, b = b, a + b
    fib = fibonacci()
    print([next(fib) for i in range(10)]) # >=python 3.0
    print(fib.__next__() for i in range(10)]) # >=python 3.0
    print(fib.next() for i in range(10)]) # <python 3.0





  • 相关阅读:
    第一天 学习绪论
    我的java学习道路
    windows2003 iis+dedecms 4.0701版本,登录后台显示空白
    iis+php+mysql
    net 连mysql奇怪问题
    Windows 2008安装SQL 2008图解
    注册码
    [VS2013]如何闪开安装VS2013必须要有安装IE10的限制
    net SqlBulkCopy拷贝数据的问题
    Android应用与系统安全防御
  • 原文地址:https://www.cnblogs.com/fengkang1008/p/5046618.html
Copyright © 2020-2023  润新知