[英]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.