簡體   English   中英

如何實現這個python生成器

[英]How to implement this python generator

我嘗試在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]

如果您想保持最初的想法但沒有“ if ... elif ... else”結構,請執行以下操作:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM