简体   繁体   中英

How to implement this python generator

I try to create a generator in python who returns this :

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]

This is what I have at the moment :

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)

But it seems not clean ... Is there another way around?

I'd construct the range piecewise:

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]

If you want to stay close to your original idea but without the "if...elif...else" structure:

def myGenerator(index) :
    yield 0
    yield 1/3.0
    for i in xrange(1, index-3):
        yield i
    yield index - 3 - 1/3.0
    yield index - 3

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM