1. 程式人生 > >python 叠代器 第二部分

python 叠代器 第二部分

python






#!/usr/bin/python
# coding:utf-8

#共有9道題

#http://pythontutor.com/visualize.html#mode=display  調試工具

#1.為什麽要用yield而不是print ,yield 循環,有print就會循環輸出幾次
#執行流程,外層for循環,然後自己循環,又一次for循環
#而且是先輸出print,然後是yield
‘‘‘
def item_iterator(embed_list):
    for item in embed_list:
        if isinstance(item, (tuple, list)):
            # print(type(item_iterator(item)))
            for item in item_iterator(item):
                yield item
        else:
            yield item

lst = (0, (1, 2), (3, (4, 5)))
for item in item_iterator(lst):
    print item
‘‘‘

#2.next放主函數,調用next()表達式的值時,其恢復點yield的值總是為None
‘‘‘
import time
def A():
    while True:
        print("----我是A函數---")
        # yield
        yield 5
        time.sleep(0.5)
        print("AAAAAAAAAAAA")
def B(c):
    while True:
        print("----我是B函數---")
        next(c)
        #next會不斷從yield處暫停和恢復
        time.sleep(0.5)
        print("BBBBBBBBBBBB")
if __name__ == ‘__main__‘:
    a = A()
    print "中斷"
    B(a)
‘‘‘

#3.next 恢復點為None,如果兩次next,那麽返回值為None
#send放入主函數,send(value)方法是將值傳給恢復點yield
‘‘‘
def framework(logic):
    try:
        it = logic()
        s = next(it)
        print "[FX] logic: ", s
        print "[FX] do something"
        it.send("async:" + s)
    except StopIteration:
        pass
def logic():
    s = "mylogic2"
    r = yield s
    print r
framework(logic)
‘‘‘

#4.next 這個因為while條件,會向下走
‘‘‘
def fibonacci():
  a,b=0,1
  while True:
      yield b
      a, b = b, a + b
fib=fibonacci()
print fib.next()
print fib.next()
print fib.next()
print [fib.next() for i in range(10)]
‘‘‘

#叠代器必須要有next,才能輸出
‘‘‘
def consumer(name):
    print("%s 準備吃包子啦!" %name)
    while True:
       baozi = yield
       print("包子[%s]來了,被[%s]吃了!" %(baozi,name))

c = consumer("alex")
c.next()
c.send`("韭菜餡")
‘‘‘

#yield + 循環   只要函數中有yield,循環的時候,那麽就是叠代器,不要使用print
‘‘‘
def item_iterator(embed_list):
    for item in embed_list:
        if isinstance(item, (tuple, list)):
            for i in item_iterator(item)
                yield i
        else:
            yield item

lst = (0, (1, 2), (3, (4, 5)))
for item in item_iterator(lst):
    print item
‘‘‘


#素數 質數定義為在大於1的自然數中,除了1和它本身以外不再有其他因數
‘‘‘
def prime_sieve(n):
    flags = [True] * n
    flags[0] = flags[1] = False
    for i in xrange(2, n):
        if flags[i]:
            yield i
            for j in xrange(2, (n - 1) / i + 1):
                flags[i * j] = False
for p in prime_sieve(100):
    print p
‘‘‘
‘‘‘
def prime_sieve(n):
    flags = {}
    for i in xrange(2, n):
        for j in xrange(2, (n - 1) / i + 1):
            if i==j and i / j == 0:
                # print i,j
                flags[i] = False
    print flags
    for key in flags.keys():
        if flags[key]:
            yield key
for i in prime_sieve(100):
    print i
‘‘‘

#yield + 循環  對一個序列進行全排列,這個例子說明yield 可以yield
‘‘‘
def permutations(li):
    if len(li) == 0:
        yield li
    else:
        for i in range(len(li)):
            li[0], li[i] = li[i], li[0]
            for item in permutations(li[1:]):
                # 有for循環,就會輸出yield內容
                # [li[0]] + item+permutations(li[1:])
                yield [li[0]] + item
for item in permutations(range(3)):
    print item
‘‘‘

#八皇後 http://blog.csdn.net/u014386870/article/details/44098151
from itertools import *
cols = range(8)
for vec in permutations(cols):
    if (8 == len(set(vec[i]+i for i in cols)) == len(set(vec[i]-i for i in cols)) == len(set(vec[i]+1 for i in cols)) == len(set(vec[i]-1 for i in cols))):
        print vec


本文出自 “要有夢想,萬一實現了呢” 博客,請務必保留此出處http://szgb17.blog.51cto.com/340201/1983825

python 叠代器 第二部分