• python小记——yield generator


    Python provides generator functions as a convenient shortcut to building iterators.

    # a generator that yields items instead of returning a list
    def firstn(n):
        num = 0
        while num < n:
            yield num
            num += 1
    
    sum_of_first_n = sum(firstn(1000000))

    Note that the expression of the number generation logic is clear and natural. It is very similar to the implementation that built a list in memory, but has the memory usage characteristic of the iterator implementation.

    built a list:

    # Build and return a list
    def firstn(n):
        num, nums = 0, []
        while num < n:
            nums.append(num)
            num += 1
        return nums
    
    sum_of_first_n = sum(firstn(1000000))

    generator class:

    # Using the generator pattern (an iterable)
    class firstn(object):
        def __init__(self, n):
            self.n = n
            self.num = 0
    
        def __iter__(self):
            return self
    
        # Python 3 compatibility
        def __next__(self):
            return self.next()
    
        def next(self):
            if self.num < self.n:
                cur, self.num = self.num, self.num+1
                return cur
            else:
                raise StopIteration()
    
    sum_of_first_n = sum(firstn(1000000))

    Note: the above code is perfectly acceptable for expository purposes, but remember that in Python 2 firstn() is equivalent to the built-in xrange() function, and in Python 3 range() is an immutable sequence type. The built-ins will always be much faster. SH

    Simply, generator using yield keyword is more simple and clear, you can think this as the compiler built a list in the memory with a iterator for you. It's wirtten as a function without a return statement, but used like list with iterator.

    Another exmaple:

    # explicitly write a generator function
    def double(L):
        for x in L:
            yield x*2
    
    # eggs will be a generator
    eggs = double([1, 2, 3, 4, 5])
    
    # the above is equivalent to ("generator comprehension"?)
    eggs = (x*2 for x in [1, 2, 3, 4, 5])
    
    # need to do this if you need a list
    eggs = list(double([1, 2, 3, 4, 5]))
    
    # the above is equivalent to (list comprehension)
    eggs = [x*2 for x in [1, 2, 3, 4, 5]]
  • 相关阅读:
    在 Java SE 6 中监视和诊断性能问题
    Codeforces Round #491 (Div. 2)部分题解
    BZOJ1607: [Usaco2008 Dec]Patting Heads 轻拍牛头(模拟 调和级数)
    BZOj1261: [SCOI2006]zh_tree(dp)
    BZOJ1569: [JSOI2008]Blue Mary的职员分配(dp 暴力)
    BZOJ4300: 绝世好题(dp)
    树上莫队算法
    SPOJ COT2
    BZOJ1086: [SCOI2005]王室联邦(贪心,分块?)
    Educational Codeforces Round 42 (Rated for Div. 2)
  • 原文地址:https://www.cnblogs.com/yuelien/p/13798835.html
Copyright © 2020-2023  润新知