Skip to main content
 首页 » 编程设计

python之如何实现这个python生成器

2025年05月04日20zhoujg

我尝试在 python 中创建一个返回这个的生成器:

itemList = [] 
for i in myGenerator(12): 
    itemList.append(i) 
print itemList 
>>> [0 0.334, 1, 2, 3, 4, 5, 6, 7, 8, 8.667, 9] 

这是我目前拥有的:

def myGenerator(index) : 
    indexList = xrange(index) 
    for i in indexList : 
        if i == 0: 
            yield 0 
        elif i == 1: 
            yield i/3.0 
        elif i == indexList[-2]: 
            yield indexList[-3] - (1 / 3.0) 
        elif i == indexList[-1]: 
             yield i-2 
        else : 
            yield i-1 
 
for i in myGenerator(12): 
    print(i) 

但是好像不太干净……还有别的办法吗?

请您参考如下方法:

我将分段构建范围:

from itertools import chain 
def myGenerator(index): 
    return chain([0, 1 / 3.0], xrange(1, index - 3), [index - 3 - 1 / 3.0, index - 3]) 
 
list(myGenerator(12)) 
[0, 0.33333333333333331, 1, 2, 3, 4, 5, 6, 7, 8, 8.6666666666666661, 9]