嵌套迭代器上的islice

时间:2013-01-14 15:43:57

标签: python python-2.7 iterator

我正在尝试使用Python 2.7在How to automatically generate N "distinct" colors?末尾重用该解决方案。

不幸的是,下面的代码永远不会返回,因为即使islice()请求前100次迭代,内部地图似乎也会调用

gethsvs = lambda: flatten(itertools.imap(genhsv, getfracs()))

强制进行所有迭代。有没有一种方法可以在主代码上进行islice()调用,而不是将迭代次数传递给所有lambda函数,如下所示,但是它只能在所有内部映射中获得前100次迭代? / p>

import colorsys, itertools, numpy as np
from fractions import Fraction

def zenos_dichotomy():
    '''
http://en.wikipedia.org/wiki/1/2_%2B_1/4_%2B_1/8_%2B_1/16_%2B_%C2%B7_%C2%B7_%C2%B7
    '''
    for k in itertools.count():
        yield Fraction(1, 2 ** k)

def getfracs():
    '''
    [Fraction(0, 1), Fraction(1, 2), Fraction(1, 4), Fraction(3, 4), Fraction(1, 8), Fraction(3, 8), Fraction(5, 8), Fraction(7, 8), Fraction(1, 16), Fraction(3, 16), ...]
    [0.0, 0.5, 0.25, 0.75, 0.125, 0.375, 0.625, 0.875, 0.0625, 0.1875, ...]
    '''
    yield 0
    for k in zenos_dichotomy():
        i = k.denominator # [1,2,4,8,16,...]
        for j in range(1, i, 2):
            yield Fraction(j, i)

'''Can be used for the v in hsv to map linear values 0..1 to something that looks equidistant.'''
bias = lambda x: (np.sqrt(x / 3) / Fraction(2, 3) + Fraction(1, 3)) / Fraction(6, 5)

def genhsv(h):
    for s in [Fraction(6, 10)]: # optionally use range
        for v in [Fraction(8, 10), Fraction(5, 10)]: # could use range too
            yield (h, s, v) # use bias for v here if you use range

genrgb = lambda x: colorsys.hsv_to_rgb(*x)
flatten = itertools.chain.from_iterable
gethsvs = lambda: flatten(itertools.imap(genhsv, getfracs()))
getrgbs = lambda: itertools.imap(genrgb, gethsvs())

def genhtml(x):
    uint8tuple = itertools.imap(lambda y: int(y * 255), x)
    return 'rgb({},{},{})'.format(*uint8tuple)

gethtmlcolors = lambda: map(genhtml, getrgbs())

if __name__ == '__main__':
    print(list(itertools.islice(gethtmlcolors(), 100)))

1 个答案:

答案 0 :(得分:2)

您在map() lambda中使用的是itertools.imap()而不是gethtmlcolors

gethtmlcolors = lambda: map(genhtml, getrgbs())

在python 2中,map()将尝试处理输入可迭代的所有元素。改变使用imap(),一切正常:

gethtmlcolors = lambda: itertools.imap(genhtml, getrgbs())