迭代器product

来源:互联网 发布:数据分析师主要做什么 编辑:程序博客网 时间:2024/06/06 19:29
from itertools import productpinyin_list = [[u'shei shi', u'shui shi'], [u'kai fa'], [u'jiao cheng']]keys = []for i in range(len(pinyin_list)):    tmp_keys = [item for item in pinyin_list[i]]    # print tmp_keys    if i >= 1:        keys = [' '.join(item) for item in product(keys, tmp_keys)]        # print keys    else:        keys = tmp_keysprint keys

product(iter1, iter2, ... iterN, [repeat=1]):创建一个迭代器,生成表示item1,item2等中的项目的笛卡尔积的元组,repeat是一个关键字参数,指定重复生成序列的次数。1  def product(*args, **kwds):2      # product('ABCD', 'xy') --> Ax Ay Bx By Cx Cy Dx Dy3      # product(range(2), repeat=3) --> 000 001 010 011 100 101 110 1114      pools = map(tuple, args) * kwds.get('repeat', 1)5      result = [[]]6      for pool in pools:7          result = [x+[y] for x in result for y in pool]8      for prod in result:9          yield tuple(prod)
神奇的迭代器。。。


0 0
原创粉丝点击